From alan.gauld at btinternet.com  Thu Jul  1 02:14:05 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 1 Jul 2010 01:14:05 +0100
Subject: [Tutor] Decorators
References: <AANLkTinYAmx4wW8qmZgjbnXdD4az24h3JellOx6oYtn3@mail.gmail.com>
Message-ID: <i0gmka$r99$1@dough.gmane.org>


"Mary Morris" <marris1031 at gmail.com> wrote

> anything.  I need to find out every decorator and make sure it has a
> descriptive name.  I was thinking I could write a simple script 
> which would
> parse through all of the source files and find decorators-maybe by 
> looking
> for the @ symbol?

I would first try a good IDE. I don't have it installed at the moment 
but I
think pydev for Eclipse can find decorator definitions. Combined with
a power search to locate all uses of decorators that might be easier.

Just a thought and I might be remembering wrong. But if you are doing
serious Python coding Eclipse and PyDev are a good combination.

It should also be possible to get GNU tags to handle decoratiors too - 
it
already works with Pythion and vim will work with tags...

In other words don't be too quick to jump to a programming solution,
OS level tools may be a better first step. Especially if you are on 
*nix.

HTH,

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



From rdmoores at gmail.com  Thu Jul  1 10:26:21 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Thu, 1 Jul 2010 01:26:21 -0700
Subject: [Tutor] puzzled by Python 3's print()
Message-ID: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com>

>>> x = 2000000000000034
>>> x/2
1000000000000017.0
>>> print(x/2)
1e+15

I was expecting, in fact needing, 1000000000000000017 or 1000000000000000017.0

1e+15 is unsatisfactory. Am I forced to use the decimal module?

Dick Moores

From shantanoo at gmail.com  Thu Jul  1 10:41:40 2010
From: shantanoo at gmail.com (=?UTF-8?B?4KS24KSC4KSk4KSo4KWCIChTaGFudGFub28p?=)
Date: Thu, 1 Jul 2010 14:11:40 +0530
Subject: [Tutor] puzzled by Python 3's print()
In-Reply-To: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com>
References: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com>
Message-ID: <AANLkTilvd4Vv7mJsD5DCZj_e428cccr12p1LE5Ns7JQE@mail.gmail.com>

without using decimal module:

>>> x = 2000000000000034
>>> print('%d'%(x/2))
1000000000000017


On Thu, Jul 1, 2010 at 13:56, Richard D. Moores <rdmoores at gmail.com> wrote:
>>>> x = 2000000000000034
>>>> x/2
> 1000000000000017.0
>>>> print(x/2)
> 1e+15
>
> I was expecting, in fact needing, 1000000000000000017 or 1000000000000000017.0
>
> 1e+15 is unsatisfactory. Am I forced to use the decimal module?
>
> Dick Moores
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From evert.rol at gmail.com  Thu Jul  1 10:45:31 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 1 Jul 2010 10:45:31 +0200
Subject: [Tutor] puzzled by Python 3's print()
In-Reply-To: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com>
References: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com>
Message-ID: <824DFA15-D0D8-49ED-B1D2-D57350BEBBB5@gmail.com>

>>>> x = 2000000000000034
>>>> x/2
> 1000000000000017.0
>>>> print(x/2)
> 1e+15
> 
> I was expecting, in fact needing, 1000000000000000017 or 1000000000000000017.0
> 
> 1e+15 is unsatisfactory. Am I forced to use the decimal module?

Can't you use string formatting? Eg:
>>> print("{0:15.0f}".format(x/2))
1000000000000017


print uses __str__()/str(), which I assume was deemed unsatisfactory in Python 2: it's supposed to show a 'simple, nice' representation of anything, while __repr__() (or the repr() function) shows a more exact representation (or rather, repr() shows an object that can be used to recreate a new identical object: float(repr(x/2)) gives back the correct float, while float(str(x/2)) wouldn't). 
So they've apparently changed __str__() to make things somewhat more readable. __repr__()/repr() is what you get with just using x/2 on the command line:

>>> x/2
1000000000000017.0
>>> repr(x/2)
1000000000000017.0


And you could actually use:

>>> print(repr(x/2))
1000000000000017.0


I would go for the format statement, though. But that may depend on your precise needs.


From steve at pearwood.info  Thu Jul  1 13:57:15 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 1 Jul 2010 21:57:15 +1000
Subject: [Tutor] puzzled by Python 3's print()
In-Reply-To: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com>
References: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com>
Message-ID: <201007012157.15813.steve@pearwood.info>

On Thu, 1 Jul 2010 06:26:21 pm Richard D. Moores wrote:
> >>> x = 2000000000000034
> >>> x/2
> 1000000000000017.0
>
> >>> print(x/2)
> 1e+15
>
> I was expecting, in fact needing, 1000000000000000017 or
> 1000000000000000017.0
>
> 1e+15 is unsatisfactory. Am I forced to use the decimal module?

This is not an issue with print, this is an issue with floats -- they 
produced a rounded, approximate value when converted to a string. print 
merely prints that string:

>>> x = 1e15 +17
>>> x
1000000000000017.0
>>> print(x)
1e+15
>>> str(x)
'1e+15'


If you want more control over the string conversion, you can do 
something like this:

>>> print(repr(x))
1000000000000017.0
>>> print('%.5f' % x)
1000000000000017.00000


-- 
Steven D'Aprano

From rdmoores at gmail.com  Thu Jul  1 15:11:21 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Thu, 1 Jul 2010 06:11:21 -0700
Subject: [Tutor] puzzled by Python 3's print()
In-Reply-To: <201007012157.15813.steve@pearwood.info>
References: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com> 
	<201007012157.15813.steve@pearwood.info>
Message-ID: <AANLkTiksSDjDzU_uIPyKAjAUUSAvosouLUtNiyzLxHSI@mail.gmail.com>

On Thu, Jul 1, 2010 at 04:57, Steven D'Aprano <steve at pearwood.info> wrote:
> On Thu, 1 Jul 2010 06:26:21 pm Richard D. Moores wrote:
>> >>> x = 2000000000000034
>> >>> x/2
>> 1000000000000017.0
>>
>> >>> print(x/2)
>> 1e+15
>>
>> I was expecting, in fact needing, 1000000000000000017 or
>> 1000000000000000017.0
>>
>> 1e+15 is unsatisfactory. Am I forced to use the decimal module?
>
> This is not an issue with print, this is an issue with floats -- they
> produced a rounded, approximate value when converted to a string. print
> merely prints that string:
>
>>>> x = 1e15 +17
>>>> x
> 1000000000000017.0
>>>> print(x)
> 1e+15
>>>> str(x)
> '1e+15'
>
>
> If you want more control over the string conversion, you can do
> something like this:
>
>>>> print(repr(x))
> 1000000000000017.0
>>>> print('%.5f' % x)
> 1000000000000017.00000

Thanks to yours and others responses, I've learned some things I
didn't know, but remember, I'm starting with long ints such as
x = 2000000000000034, cutting it in half, and hoping to print
1000000000000017 or 1000000000000017.0
(I also need to divide odd ints like 2000000000000033 and print
1000000000000017.5)

(In my initial post, I used a smaller x, x = 2000000000000034.  I
should have made it longer, to reflect the ints I'm dealing with (big
primes and their near neighbors).

I'm still hoping to be saved from the decimal module :)  .

Dick

From breamoreboy at yahoo.co.uk  Thu Jul  1 18:25:23 2010
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Thu, 01 Jul 2010 17:25:23 +0100
Subject: [Tutor] puzzled by Python 3's print()
In-Reply-To: <AANLkTiksSDjDzU_uIPyKAjAUUSAvosouLUtNiyzLxHSI@mail.gmail.com>
References: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com>
	<201007012157.15813.steve@pearwood.info>
	<AANLkTiksSDjDzU_uIPyKAjAUUSAvosouLUtNiyzLxHSI@mail.gmail.com>
Message-ID: <i0ifhr$e86$1@dough.gmane.org>

On 01/07/2010 14:11, Richard D. Moores wrote:
> On Thu, Jul 1, 2010 at 04:57, Steven D'Aprano<steve at pearwood.info>  wrote:
>> On Thu, 1 Jul 2010 06:26:21 pm Richard D. Moores wrote:
>>>>>> x = 2000000000000034
>>>>>> x/2
>>> 1000000000000017.0
>>>
>>>>>> print(x/2)
>>> 1e+15
>>>
>>> I was expecting, in fact needing, 1000000000000000017 or
>>> 1000000000000000017.0
>>>
>>> 1e+15 is unsatisfactory. Am I forced to use the decimal module?
>>
>> This is not an issue with print, this is an issue with floats -- they
>> produced a rounded, approximate value when converted to a string. print
>> merely prints that string:
>>
>>>>> x = 1e15 +17
>>>>> x
>> 1000000000000017.0
>>>>> print(x)
>> 1e+15
>>>>> str(x)
>> '1e+15'
>>
>>
>> If you want more control over the string conversion, you can do
>> something like this:
>>
>>>>> print(repr(x))
>> 1000000000000017.0
>>>>> print('%.5f' % x)
>> 1000000000000017.00000
>
> Thanks to yours and others responses, I've learned some things I
> didn't know, but remember, I'm starting with long ints such as
> x = 2000000000000034, cutting it in half, and hoping to print
> 1000000000000017 or 1000000000000017.0
> (I also need to divide odd ints like 2000000000000033 and print
> 1000000000000017.5)
>
> (In my initial post, I used a smaller x, x = 2000000000000034.  I
> should have made it longer, to reflect the ints I'm dealing with (big
> primes and their near neighbors).
>
> I'm still hoping to be saved from the decimal module :)  .

I think that we can manage that. :)

>
> Dick
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Take a look at section 7.1.3 here.

http://docs.python.org/py3k/library/string.html#string-formatting

This is the recommended way to format strings in Python 3.

Kindest regards.

Mark Lawrence.


From rdmoores at gmail.com  Thu Jul  1 18:58:57 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Thu, 1 Jul 2010 09:58:57 -0700
Subject: [Tutor] puzzled by Python 3's print()
In-Reply-To: <i0ifhr$e86$1@dough.gmane.org>
References: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com> 
	<201007012157.15813.steve@pearwood.info>
	<AANLkTiksSDjDzU_uIPyKAjAUUSAvosouLUtNiyzLxHSI@mail.gmail.com> 
	<i0ifhr$e86$1@dough.gmane.org>
Message-ID: <AANLkTik4MW8uCjctX60yAnttRnMuAx4N_8f_Bl-YEwmF@mail.gmail.com>

On Thu, Jul 1, 2010 at 09:25, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:

> Take a look at section 7.1.3 here.
>
> http://docs.python.org/py3k/library/string.html#string-formatting
>
> This is the recommended way to format strings in Python 3.

Thanks, Mark. Looks good, if cryptic. I don't have time to dig into it
 now, but I will later and report back.

Dick

From eike.welk at gmx.net  Thu Jul  1 21:18:00 2010
From: eike.welk at gmx.net (Eike Welk)
Date: Thu, 1 Jul 2010 21:18:00 +0200
Subject: [Tutor] puzzled by Python 3's print()
In-Reply-To: <AANLkTiksSDjDzU_uIPyKAjAUUSAvosouLUtNiyzLxHSI@mail.gmail.com>
References: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com>
	<201007012157.15813.steve@pearwood.info>
	<AANLkTiksSDjDzU_uIPyKAjAUUSAvosouLUtNiyzLxHSI@mail.gmail.com>
Message-ID: <201007012118.00311.eike.welk@gmx.net>

Hello Richard!

On Thursday July 1 2010 15:11:21 Richard D. Moores wrote:
> Thanks to yours and others responses, I've learned some things I
> didn't know, but remember, I'm starting with long ints such as

Also note that in Python 3 the "/" (division) operator returns a floating 
point number when you divide integers. This is one of the changes that Python 
3 introduces.

As you are using long integers (and you were previously writing about prime 
numbers) the precision of floating point numbers might not be enough for your 
purposes.

Therefore you should probably use the integer division operator: "//"


The following (edited) snippet from IPython demonstrates "//" and the loss of 
precision when using "/":


...
Python 2.6.2 (r262:71600, Mar 29 2010, 15:30:01)
Type "copyright", "credits" or "license" for more information.

IPython 0.10 -- An enhanced Interactive Python.
...

In [1]: from __future__ import  division

In [2]: a = 1000000000000000000000000000000000000000000000000000000002

In [3]: a
Out[3]: 1000000000000000000000000000000000000000000000000000000002L

In [4]: a//2
Out[4]: 500000000000000000000000000000000000000000000000000000001L

In [5]: a/2
Out[5]: 4.9999999999999994e+56

In [6]: long(a/2)
Out[6]: 499999999999999937061060126016582882140297920412594995200L


Eike.

From breamoreboy at yahoo.co.uk  Thu Jul  1 23:13:54 2010
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Thu, 01 Jul 2010 22:13:54 +0100
Subject: [Tutor] puzzled by Python 3's print()
In-Reply-To: <201007012118.00311.eike.welk@gmx.net>
References: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com>	<201007012157.15813.steve@pearwood.info>	<AANLkTiksSDjDzU_uIPyKAjAUUSAvosouLUtNiyzLxHSI@mail.gmail.com>
	<201007012118.00311.eike.welk@gmx.net>
Message-ID: <i0j0eq$cb6$1@dough.gmane.org>

On 01/07/2010 20:18, Eike Welk wrote:
> Hello Richard!
>
> On Thursday July 1 2010 15:11:21 Richard D. Moores wrote:
>> Thanks to yours and others responses, I've learned some things I
>> didn't know, but remember, I'm starting with long ints such as
>
> Also note that in Python 3 the "/" (division) operator returns a floating
> point number when you divide integers. This is one of the changes that Python
> 3 introduces.
>
> As you are using long integers (and you were previously writing about prime
> numbers) the precision of floating point numbers might not be enough for your
> purposes.
>
> Therefore you should probably use the integer division operator: "//"
>
>
> The following (edited) snippet from IPython demonstrates "//" and the loss of
> precision when using "/":
>
>
> ...
> Python 2.6.2 (r262:71600, Mar 29 2010, 15:30:01)
> Type "copyright", "credits" or "license" for more information.
>
> IPython 0.10 -- An enhanced Interactive Python.
> ...
>
> In [1]: from __future__ import  division
>
> In [2]: a = 1000000000000000000000000000000000000000000000000000000002
>
> In [3]: a
> Out[3]: 1000000000000000000000000000000000000000000000000000000002L
>
> In [4]: a//2
> Out[4]: 500000000000000000000000000000000000000000000000000000001L
>
> In [5]: a/2
> Out[5]: 4.9999999999999994e+56
>
> In [6]: long(a/2)
> Out[6]: 499999999999999937061060126016582882140297920412594995200L
>
>
> Eike.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Drat, drat and double drat, I believe Dick Dastardly from the Wacky 
Races cartoons.  I meant to mention this, got side-tracked and 
completely forgot, sorry.

Kindest regards.

Mark Lawrence.


From rdmoores at gmail.com  Thu Jul  1 23:57:52 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Thu, 1 Jul 2010 14:57:52 -0700
Subject: [Tutor] puzzled by Python 3's print()
In-Reply-To: <201007012118.00311.eike.welk@gmx.net>
References: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com> 
	<201007012157.15813.steve@pearwood.info>
	<AANLkTiksSDjDzU_uIPyKAjAUUSAvosouLUtNiyzLxHSI@mail.gmail.com> 
	<201007012118.00311.eike.welk@gmx.net>
Message-ID: <AANLkTimh2CSZbpubPRs8GMRtAbynEbGTnMH8bdDlu3ML@mail.gmail.com>

On Thu, Jul 1, 2010 at 12:18, Eike Welk <eike.welk at gmx.net> wrote:

> Therefore you should probably use the integer division operator: "//"

>>> x = 200000000000000000000000000000000000000033
>>> x//2
100000000000000000000000000000000000000016

I can live with THAT error!

Thanks, Eike!

But I will press on with Mark's
<http://docs.python.org/py3k/library/string.html#string-formatting>

Dick

From kb1pkl at aim.com  Fri Jul  2 00:05:35 2010
From: kb1pkl at aim.com (Corey Richardson)
Date: Thu, 01 Jul 2010 18:05:35 -0400
Subject: [Tutor] S.find()
Message-ID: <4C2D112F.7080208@aim.com>

Hello Tutors!
    I'm having a problem with the find() method of string objects. I'm 
currently making a hangman game, and I'm making the part that finds
if there are multiple copies of the guessed letter in the word, and then 
if there are, finds them all. I can't for the life of me figure out the
syntax of the find() method. gameWord = "python", btw.

    The module documentation lists it as this: "S.find(sub[, start[, 
end]]) -> int".
    I'm assuming sub is the string you want to find, and that is how it 
has worked out for me. (Bonus Points: What does sub mean? I'm guessing 
subscriptable, as one of my errors says, but I'll get to that...)
   When I try gameWord.find('p'[,1[,3]]), as the little help box 
suggests, I get this:

SyntaxError: invalid syntax

Ok then, that is the exact syntax I was given. My next try is, and 
gives, this:

 >>> gameWord.find('p', [1,[3]])

Traceback (most recent call last):
  File "<pyshell#99>", line 1, in <module>
    gameWord.find('p', [1,[3]])
TypeError: slice indices must be integers or None or have an __index__ 
method


I assumed the comma after the 1 was messing it up, so I put this:

 >>> gameWord.find("p", [1[3]])
Traceback (most recent call last):
  File "<pyshell#101>", line 1, in <module>
    gameWord.find("p", [1[3]])
TypeError: 'int' object is not subscriptable

Is subscriptable what sup stands for in find()? What does mean? (5 Bonus 
Points for answering that).

I also tried passing a slice index right into it like gameWord.find('p', 
[1:4]), but that returned a SyntaxError as well.

    I have the entirety of my code posted up at 
http://pastebin.com/k9nMZNMy, I won't edit the code until I get this 
worked out, except maybe a few housekeeping things, documentation, etc.*

*I've tried everything I can, and I appreciate your time and help!

~Corey Richardson


From breamoreboy at yahoo.co.uk  Fri Jul  2 00:55:45 2010
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Thu, 01 Jul 2010 23:55:45 +0100
Subject: [Tutor] S.find()
In-Reply-To: <4C2D112F.7080208@aim.com>
References: <4C2D112F.7080208@aim.com>
Message-ID: <i0j6dq$ub1$1@dough.gmane.org>

On 01/07/2010 23:05, Corey Richardson wrote:
> Hello Tutors!
> I'm having a problem with the find() method of string objects. I'm
> currently making a hangman game, and I'm making the part that finds
> if there are multiple copies of the guessed letter in the word, and then
> if there are, finds them all. I can't for the life of me figure out the
> syntax of the find() method. gameWord = "python", btw.
>
> The module documentation lists it as this: "S.find(sub[, start[, end]])
> -> int".

What version of Python are you using?  For Python 2.6.5 on Windows I 
have from the compiled help file.

"
str.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found, such 
that sub is contained in the range [start, end]. Optional arguments 
start and end are interpreted as in slice notation. Return -1 if sub is 
not found.
"

> I'm assuming sub is the string you want to find, and that is how it has
> worked out for me. (Bonus Points: What does sub mean? I'm guessing

See above.

> subscriptable, as one of my errors says, but I'll get to that...)
> When I try gameWord.find('p'[,1[,3]]), as the little help box suggests,

You don't need the square brackets, they're used in many forms of 
documentation to indicate an optional argument.

> I get this:
>
> SyntaxError: invalid syntax
>
> Ok then, that is the exact syntax I was given. My next try is, and
> gives, this:
>
>  >>> gameWord.find('p', [1,[3]])
>
> Traceback (most recent call last):
> File "<pyshell#99>", line 1, in <module>
> gameWord.find('p', [1,[3]])
> TypeError: slice indices must be integers or None or have an __index__
> method
>
>
> I assumed the comma after the 1 was messing it up, so I put this:
>
>  >>> gameWord.find("p", [1[3]])
> Traceback (most recent call last):
> File "<pyshell#101>", line 1, in <module>
> gameWord.find("p", [1[3]])
> TypeError: 'int' object is not subscriptable
>
> Is subscriptable what sup stands for in find()? What does mean? (5 Bonus
> Points for answering that).

I'd prefer 5 bonus pints, but the documentation quoted above means I 
couldn't really accept.  Alright then, twist my arm if you must. :)

>
> I also tried passing a slice index right into it like gameWord.find('p',
> [1:4]), but that returned a SyntaxError as well.
>
> I have the entirety of my code posted up at
> http://pastebin.com/k9nMZNMy, I won't edit the code until I get this
> worked out, except maybe a few housekeeping things, documentation, etc.*
>
> *I've tried everything I can, and I appreciate your time and help!
>
> ~Corey Richardson
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Kindest regards.

Mark Lawrence.



From steve at pearwood.info  Fri Jul  2 01:18:27 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 2 Jul 2010 09:18:27 +1000
Subject: [Tutor] puzzled by Python 3's print()
In-Reply-To: <201007012118.00311.eike.welk@gmx.net>
References: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com>
	<AANLkTiksSDjDzU_uIPyKAjAUUSAvosouLUtNiyzLxHSI@mail.gmail.com>
	<201007012118.00311.eike.welk@gmx.net>
Message-ID: <201007020918.27847.steve@pearwood.info>

On Fri, 2 Jul 2010 05:18:00 am Eike Welk wrote:

> As you are using long integers (and you were previously writing about
> prime numbers) the precision of floating point numbers might not be
> enough for your purposes.

It certainly won't be once you get to large enough primes!

> Therefore you should probably use the integer division operator: "//"

And the reminder (or modulo) operator %, together with the combination 
function divmod(a, b) which returns (a//b, a%b). The advantage of 
divmod is that it is faster than calling a//b followed by a%b.


-- 
Steven D'Aprano

From steve at pearwood.info  Fri Jul  2 01:33:02 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 2 Jul 2010 09:33:02 +1000
Subject: [Tutor] S.find()
In-Reply-To: <4C2D112F.7080208@aim.com>
References: <4C2D112F.7080208@aim.com>
Message-ID: <201007020933.02299.steve@pearwood.info>

On Fri, 2 Jul 2010 08:05:35 am Corey Richardson wrote:
> Hello Tutors!
>     I'm having a problem with the find() method of string objects.
[...]
>     The module documentation lists it as this: "S.find(sub[, start[,
> end]]) -> int".
>     I'm assuming sub is the string you want to find, and that is how
> it has worked out for me. (Bonus Points: What does sub mean? 

"substring"

> I'm 
> guessing subscriptable, as one of my errors says, but I'll get to
> that...) When I try gameWord.find('p'[,1[,3]]), as the little help
> box suggests, I get this:
>
> SyntaxError: invalid syntax

There's a skill you need to read documentation. In particular, you need 
to know one small fact, without which function signatures like 

S.find(sub[, start[, end]]) -> int

are totally mysterious. That is that square brackets [ ] are used to 
show optional arguments, and you don't type them! In Python, square 
brackets make lists, and the would-be-list [, 1[, [3]] is malformed, 
hence the Syntax error.

This shows that the method takes one compulsory argument (sub), 
optionally followed by either one optional argument (start) or two 
(start and end), and returns an integer result. So the example above is 
equivalent to three examples:

S.find(sub) -> int
S.find(sub, start) -> int
S.find(sub, start, end) -> int

Don't forget that indexes in Python start counting from 0, not 1, so 
passing 1 as the starting index means you skip the first character.


> Ok then, that is the exact syntax I was given. My next try is, and
>
> gives, this:
>  >>> gameWord.find('p', [1,[3]])
>
> Traceback (most recent call last):
>   File "<pyshell#99>", line 1, in <module>
>     gameWord.find('p', [1,[3]])
> TypeError: slice indices must be integers or None or have an
> __index__ method

Now you use properly formed lists, but the start argument (if given) 
can't be a list [1, [3]]. It has to be an integer, or None, or some 
object which is convertable to an integer using the __index__ method:

> I assumed the comma after the 1 was messing it up, so I put this:
>  >>> gameWord.find("p", [1[3]])
>
> Traceback (most recent call last):
>   File "<pyshell#101>", line 1, in <module>
>     gameWord.find("p", [1[3]])
> TypeError: 'int' object is not subscriptable

To Python, it looks like you're passing as the start argument a list 
containing a single value, which is the 3rd element of the int 1. But 
ints don't have elements and so can't be subscripted like 1[3], hence 
the error.



-- 
Steven D'Aprano

From rdmoores at gmail.com  Fri Jul  2 05:34:43 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Thu, 1 Jul 2010 20:34:43 -0700
Subject: [Tutor] puzzled by Python 3's print()
In-Reply-To: <201007020918.27847.steve@pearwood.info>
References: <AANLkTilKKSiCaIkt-RTbkVpvY8zJQaroOKQysD7OWpiE@mail.gmail.com> 
	<AANLkTiksSDjDzU_uIPyKAjAUUSAvosouLUtNiyzLxHSI@mail.gmail.com> 
	<201007012118.00311.eike.welk@gmx.net>
	<201007020918.27847.steve@pearwood.info>
Message-ID: <AANLkTinRPr0etxrg26288UFvW7IZzvdXHk2rLAenoGK3@mail.gmail.com>

On Thu, Jul 1, 2010 at 16:18, Steven D'Aprano <steve at pearwood.info> wrote:
> On Fri, 2 Jul 2010 05:18:00 am Eike Welk wrote:
>
>> As you are using long integers (and you were previously writing about
>> prime numbers) the precision of floating point numbers might not be
>> enough for your purposes.
>
> It certainly won't be once you get to large enough primes!
>
>> Therefore you should probably use the integer division operator: "//"
>
> And the reminder (or modulo) operator %, together with the combination
> function divmod(a, b) which returns (a//b, a%b). The advantage of
> divmod is that it is faster than calling a//b followed by a%b.

Thanks to you and Eike, Steven, I was able to write this little
function that does the job for me, and more:

>>> def divide_large_ints(n, div):
	    x = divmod(n, div)
	    return str(x[0]) + str(x[1]/div).lstrip('0')

	
>>> n = 2000000000000000000000000000000033
>>> div = 2
>>> divide_large_ints(n, div)
'1000000000000000000000000000000016.5'
>>>

Dick

From rdmoores at gmail.com  Fri Jul  2 05:57:53 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Thu, 1 Jul 2010 20:57:53 -0700
Subject: [Tutor] (no subject)
In-Reply-To: <i0g666$o8$1@dough.gmane.org>
References: <AANLkTinH0PTFxhSbQrwiUjML8NMuzCDcpQxScIRhct35@mail.gmail.com> 
	<i0g666$o8$1@dough.gmane.org>
Message-ID: <AANLkTik0umnTHzg4-luIytzPLT36g1rG-If2rt1G63XE@mail.gmail.com>

On Wed, Jun 30, 2010 at 12:33, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Aaron Chambers" <a.pringles.can at gmail.com> wrote in message
> news:AANLkTinH0PTFxhSbQrwiUjML8NMuzCDcpQxScIRhct35 at mail.gmail.com...
>>
>> I'm new to Python, and wanted to start messing around with it, but the
>> computer I'm using is running Windows 7, so is there a version of Python
>> that's compatible with 7?
>
> Yes, and I would recommend you get yours from the Activestate.com
> web site rather than python.org since the Activestate version is much
> more Windows friendly.

Alan, I'm interested. Could you tell us more about how it's more
Windows friendly?

BTW I just tried to install ActivePython 3.1.2.3 (Win 64-bit x64), and
waited more than 10 minutes while the installation program checked on
space on my laptop. I used Task Manager to stop it. Will try again
later.

Dick

From alan.gauld at btinternet.com  Fri Jul  2 09:56:30 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 2 Jul 2010 08:56:30 +0100
Subject: [Tutor] (no subject)
References: <AANLkTinH0PTFxhSbQrwiUjML8NMuzCDcpQxScIRhct35@mail.gmail.com>
	<i0g666$o8$1@dough.gmane.org>
	<AANLkTik0umnTHzg4-luIytzPLT36g1rG-If2rt1G63XE@mail.gmail.com>
Message-ID: <i0k63c$9qp$1@dough.gmane.org>


"Richard D. Moores" <rdmoores at gmail.com> wrote

>> Yes, and I would recommend you get yours from the Activestate.com
>> web site rather than python.org since the Activestate version is 
>> much
>> more Windows friendly.
>
> Alan, I'm interested. Could you tell us more about how it's more
> Windows friendly?

It comes with the Windows extensions pre packaged as well as a
Windows help file which gives access to the usual Python docs plus
a bunch of other resources, all fully searchable etc. The installer 
also
does a better job IMHO of setting up the Windows path, start menu etc.

Its nothing critical but just makes for an easier life having all the
Windows extras etc work "out of the box".

Alan G. 



From smokefloat at gmail.com  Fri Jul  2 15:16:02 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 2 Jul 2010 09:16:02 -0400
Subject: [Tutor] Reading a file
Message-ID: <AANLkTil4QjpbnlVpnRsDMhStqAx_xdxEAemnFI3Tnb1w@mail.gmail.com>

In the code below, I'm trying to read from a file, and print out the lines.
I know I've seen the exact function I'm looking for here, but it seems
like the below 'should' work.

The second function(rdfil) works, if just the line number is placed
there, and th first(increment) works for printing a new number in
range for the rdfil to operate while going through the lines in the
file.
Any other options other than using linecache.getline(I'm sure there
are, just haven't jogged the right memory cell loose yet)?

def increment():
	for number in range(1, 500):
		print number ++1

def rdfil():
	outputfile = raw_input('Input file name: ')
	for line in outputfile:
		if line:
			readcont = linecache.getline(outputfile, increment) '''increment is
originally supposed to be an int for the line number being read'''
			print readcont

Thanks,
David

From kb1pkl at aim.com  Fri Jul  2 16:57:38 2010
From: kb1pkl at aim.com (Corey Richardson)
Date: Fri, 02 Jul 2010 10:57:38 -0400
Subject: [Tutor] S.find()
In-Reply-To: <mailman.18.1278064804.12365.tutor@python.org>
References: <mailman.18.1278064804.12365.tutor@python.org>
Message-ID: <4C2DFE62.8020806@aim.com>

Thanks everyone! I got it all working now, and I finished up the 
program. Your help is much appreciated ;-)

~Corey Richardson

From steve at pearwood.info  Fri Jul  2 17:31:22 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 3 Jul 2010 01:31:22 +1000
Subject: [Tutor] Reading a file
In-Reply-To: <AANLkTil4QjpbnlVpnRsDMhStqAx_xdxEAemnFI3Tnb1w@mail.gmail.com>
References: <AANLkTil4QjpbnlVpnRsDMhStqAx_xdxEAemnFI3Tnb1w@mail.gmail.com>
Message-ID: <201007030131.22700.steve@pearwood.info>

On Fri, 2 Jul 2010 11:16:02 pm David Hutto wrote:
> In the code below, I'm trying to read from a file, and print out the
> lines. 

f = open("filename.txt")
for line in f:
    print line
f.close()

is all you need, and even the close at the end is optional (but 
recommended).


> I know I've seen the exact function I'm looking for here, but 
> it seems like the below 'should' work.
>
> The second function(rdfil) works, if just the line number is placed
> there, and th first(increment) works for printing a new number in
> range for the rdfil to operate while going through the lines in the
> file.
> Any other options other than using linecache.getline(I'm sure there
> are, just haven't jogged the right memory cell loose yet)?
>
> def increment():
> 	for number in range(1, 500):
> 		print number ++1

Why do you have number ++1 instead of just number+1 ?

For that matter, why do you have number+1 instead of changing the range 
to range(2, 501)?


> def rdfil():
> 	outputfile = raw_input('Input file name: ')

This puts a *string* in the variable outputfile. A better name would 
be "outputfilename", because it is a file NAME, not a file.

> 	for line in outputfile:

This is terribly misleading, because iterating over a string gives you 
the individual characters of the string, not lines. E.g.:

for line in "file.txt":
    print line

will print:

f
i
l
e
.
t
x
t

> 		if line:

This will always be true, and so is pointless. Even an empty line is not 
truly empty, as it will be a newline character. When the file is empty, 
the for-loop will exit.

> 			readcont = linecache.getline(outputfile, increment) '''increment
> is originally supposed to be an int for the line number being read'''

This line gives a syntax error. What is it supposed to be? What is the 
purpose of the string? It looks like it is meant to be a comment, but 
why have you written it as a string instead of a # comment?


-- 
Steven D'Aprano

From benderjacob44 at gmail.com  Fri Jul  2 17:44:26 2010
From: benderjacob44 at gmail.com (Jacob Bender)
Date: Fri, 2 Jul 2010 11:44:26 -0400
Subject: [Tutor] Tutor Digest, Vol 77, Issue 3
In-Reply-To: <mailman.414.1278043095.1671.tutor@python.org>
References: <mailman.414.1278043095.1671.tutor@python.org>
Message-ID: <AANLkTil7GGlRSJ8vg9yMoz4KNAn19_VHmD-PUBSomDed@mail.gmail.com>

Instead of using "find" you could use a for loop. Explore what I mean in the
attachment. If you have IDLE you can look at the programming in it.

On Thu, Jul 1, 2010 at 11:58 PM, <tutor-request at python.org> wrote:

> Send Tutor mailing list submissions to
>        tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>        http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>        tutor-request at python.org
>
> You can reach the person managing the list at
>        tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>   1. S.find() (Corey Richardson)
>   2. Re: S.find() (Mark Lawrence)
>   3. Re: puzzled by Python 3's print() (Steven D'Aprano)
>   4. Re: S.find() (Steven D'Aprano)
>   5. Re: puzzled by Python 3's print() (Richard D. Moores)
>   6. Re: (no subject) (Richard D. Moores)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Thu, 01 Jul 2010 18:05:35 -0400
> From: Corey Richardson <kb1pkl at aim.com>
> To: tutor at python.org
> Subject: [Tutor] S.find()
> Message-ID: <4C2D112F.7080208 at aim.com>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Hello Tutors!
>    I'm having a problem with the find() method of string objects. I'm
> currently making a hangman game, and I'm making the part that finds
> if there are multiple copies of the guessed letter in the word, and then
> if there are, finds them all. I can't for the life of me figure out the
> syntax of the find() method. gameWord = "python", btw.
>
>    The module documentation lists it as this: "S.find(sub[, start[,
> end]]) -> int".
>    I'm assuming sub is the string you want to find, and that is how it
> has worked out for me. (Bonus Points: What does sub mean? I'm guessing
> subscriptable, as one of my errors says, but I'll get to that...)
>   When I try gameWord.find('p'[,1[,3]]), as the little help box
> suggests, I get this:
>
> SyntaxError: invalid syntax
>
> Ok then, that is the exact syntax I was given. My next try is, and
> gives, this:
>
>  >>> gameWord.find('p', [1,[3]])
>
> Traceback (most recent call last):
>  File "<pyshell#99>", line 1, in <module>
>    gameWord.find('p', [1,[3]])
> TypeError: slice indices must be integers or None or have an __index__
> method
>
>
> I assumed the comma after the 1 was messing it up, so I put this:
>
>  >>> gameWord.find("p", [1[3]])
> Traceback (most recent call last):
>  File "<pyshell#101>", line 1, in <module>
>    gameWord.find("p", [1[3]])
> TypeError: 'int' object is not subscriptable
>
> Is subscriptable what sup stands for in find()? What does mean? (5 Bonus
> Points for answering that).
>
> I also tried passing a slice index right into it like gameWord.find('p',
> [1:4]), but that returned a SyntaxError as well.
>
>    I have the entirety of my code posted up at
> http://pastebin.com/k9nMZNMy, I won't edit the code until I get this
> worked out, except maybe a few housekeeping things, documentation, etc.*
>
> *I've tried everything I can, and I appreciate your time and help!
>
> ~Corey Richardson
>
>
>
> ------------------------------
>
> Message: 2
> Date: Thu, 01 Jul 2010 23:55:45 +0100
> From: Mark Lawrence <breamoreboy at yahoo.co.uk>
> To: tutor at python.org
> Subject: Re: [Tutor] S.find()
> Message-ID: <i0j6dq$ub1$1 at dough.gmane.org>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> On 01/07/2010 23:05, Corey Richardson wrote:
> > Hello Tutors!
> > I'm having a problem with the find() method of string objects. I'm
> > currently making a hangman game, and I'm making the part that finds
> > if there are multiple copies of the guessed letter in the word, and then
> > if there are, finds them all. I can't for the life of me figure out the
> > syntax of the find() method. gameWord = "python", btw.
> >
> > The module documentation lists it as this: "S.find(sub[, start[, end]])
> > -> int".
>
> What version of Python are you using?  For Python 2.6.5 on Windows I
> have from the compiled help file.
>
> "
> str.find(sub[, start[, end]])
> Return the lowest index in the string where substring sub is found, such
> that sub is contained in the range [start, end]. Optional arguments
> start and end are interpreted as in slice notation. Return -1 if sub is
> not found.
> "
>
> > I'm assuming sub is the string you want to find, and that is how it has
> > worked out for me. (Bonus Points: What does sub mean? I'm guessing
>
> See above.
>
> > subscriptable, as one of my errors says, but I'll get to that...)
> > When I try gameWord.find('p'[,1[,3]]), as the little help box suggests,
>
> You don't need the square brackets, they're used in many forms of
> documentation to indicate an optional argument.
>
> > I get this:
> >
> > SyntaxError: invalid syntax
> >
> > Ok then, that is the exact syntax I was given. My next try is, and
> > gives, this:
> >
> >  >>> gameWord.find('p', [1,[3]])
> >
> > Traceback (most recent call last):
> > File "<pyshell#99>", line 1, in <module>
> > gameWord.find('p', [1,[3]])
> > TypeError: slice indices must be integers or None or have an __index__
> > method
> >
> >
> > I assumed the comma after the 1 was messing it up, so I put this:
> >
> >  >>> gameWord.find("p", [1[3]])
> > Traceback (most recent call last):
> > File "<pyshell#101>", line 1, in <module>
> > gameWord.find("p", [1[3]])
> > TypeError: 'int' object is not subscriptable
> >
> > Is subscriptable what sup stands for in find()? What does mean? (5 Bonus
> > Points for answering that).
>
> I'd prefer 5 bonus pints, but the documentation quoted above means I
> couldn't really accept.  Alright then, twist my arm if you must. :)
>
> >
> > I also tried passing a slice index right into it like gameWord.find('p',
> > [1:4]), but that returned a SyntaxError as well.
> >
> > I have the entirety of my code posted up at
> > http://pastebin.com/k9nMZNMy, I won't edit the code until I get this
> > worked out, except maybe a few housekeeping things, documentation, etc.*
> >
> > *I've tried everything I can, and I appreciate your time and help!
> >
> > ~Corey Richardson
> >
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
> Kindest regards.
>
> Mark Lawrence.
>
>
>
>
> ------------------------------
>
> Message: 3
> Date: Fri, 2 Jul 2010 09:18:27 +1000
> From: Steven D'Aprano <steve at pearwood.info>
> To: tutor at python.org
> Subject: Re: [Tutor] puzzled by Python 3's print()
> Message-ID: <201007020918.27847.steve at pearwood.info>
> Content-Type: text/plain;  charset="iso-8859-1"
>
> On Fri, 2 Jul 2010 05:18:00 am Eike Welk wrote:
>
> > As you are using long integers (and you were previously writing about
> > prime numbers) the precision of floating point numbers might not be
> > enough for your purposes.
>
> It certainly won't be once you get to large enough primes!
>
> > Therefore you should probably use the integer division operator: "//"
>
> And the reminder (or modulo) operator %, together with the combination
> function divmod(a, b) which returns (a//b, a%b). The advantage of
> divmod is that it is faster than calling a//b followed by a%b.
>
>
> --
> Steven D'Aprano
>
>
> ------------------------------
>
> Message: 4
> Date: Fri, 2 Jul 2010 09:33:02 +1000
> From: Steven D'Aprano <steve at pearwood.info>
> To: tutor at python.org
> Subject: Re: [Tutor] S.find()
> Message-ID: <201007020933.02299.steve at pearwood.info>
> Content-Type: text/plain;  charset="iso-8859-1"
>
> On Fri, 2 Jul 2010 08:05:35 am Corey Richardson wrote:
> > Hello Tutors!
> >     I'm having a problem with the find() method of string objects.
> [...]
> >     The module documentation lists it as this: "S.find(sub[, start[,
> > end]]) -> int".
> >     I'm assuming sub is the string you want to find, and that is how
> > it has worked out for me. (Bonus Points: What does sub mean?
>
> "substring"
>
> > I'm
> > guessing subscriptable, as one of my errors says, but I'll get to
> > that...) When I try gameWord.find('p'[,1[,3]]), as the little help
> > box suggests, I get this:
> >
> > SyntaxError: invalid syntax
>
> There's a skill you need to read documentation. In particular, you need
> to know one small fact, without which function signatures like
>
> S.find(sub[, start[, end]]) -> int
>
> are totally mysterious. That is that square brackets [ ] are used to
> show optional arguments, and you don't type them! In Python, square
> brackets make lists, and the would-be-list [, 1[, [3]] is malformed,
> hence the Syntax error.
>
> This shows that the method takes one compulsory argument (sub),
> optionally followed by either one optional argument (start) or two
> (start and end), and returns an integer result. So the example above is
> equivalent to three examples:
>
> S.find(sub) -> int
> S.find(sub, start) -> int
> S.find(sub, start, end) -> int
>
> Don't forget that indexes in Python start counting from 0, not 1, so
> passing 1 as the starting index means you skip the first character.
>
>
> > Ok then, that is the exact syntax I was given. My next try is, and
> >
> > gives, this:
> >  >>> gameWord.find('p', [1,[3]])
> >
> > Traceback (most recent call last):
> >   File "<pyshell#99>", line 1, in <module>
> >     gameWord.find('p', [1,[3]])
> > TypeError: slice indices must be integers or None or have an
> > __index__ method
>
> Now you use properly formed lists, but the start argument (if given)
> can't be a list [1, [3]]. It has to be an integer, or None, or some
> object which is convertable to an integer using the __index__ method:
>
> > I assumed the comma after the 1 was messing it up, so I put this:
> >  >>> gameWord.find("p", [1[3]])
> >
> > Traceback (most recent call last):
> >   File "<pyshell#101>", line 1, in <module>
> >     gameWord.find("p", [1[3]])
> > TypeError: 'int' object is not subscriptable
>
> To Python, it looks like you're passing as the start argument a list
> containing a single value, which is the 3rd element of the int 1. But
> ints don't have elements and so can't be subscripted like 1[3], hence
> the error.
>
>
>
> --
> Steven D'Aprano
>
>
> ------------------------------
>
> Message: 5
> Date: Thu, 1 Jul 2010 20:34:43 -0700
> From: "Richard D. Moores" <rdmoores at gmail.com>
> To: "Steven D'Aprano" <steve at pearwood.info>
> Cc: tutor at python.org
> Subject: Re: [Tutor] puzzled by Python 3's print()
> Message-ID:
>        <AANLkTinRPr0etxrg26288UFvW7IZzvdXHk2rLAenoGK3 at mail.gmail.com>
> Content-Type: text/plain; charset=UTF-8
>
> On Thu, Jul 1, 2010 at 16:18, Steven D'Aprano <steve at pearwood.info> wrote:
> > On Fri, 2 Jul 2010 05:18:00 am Eike Welk wrote:
> >
> >> As you are using long integers (and you were previously writing about
> >> prime numbers) the precision of floating point numbers might not be
> >> enough for your purposes.
> >
> > It certainly won't be once you get to large enough primes!
> >
> >> Therefore you should probably use the integer division operator: "//"
> >
> > And the reminder (or modulo) operator %, together with the combination
> > function divmod(a, b) which returns (a//b, a%b). The advantage of
> > divmod is that it is faster than calling a//b followed by a%b.
>
> Thanks to you and Eike, Steven, I was able to write this little
> function that does the job for me, and more:
>
> >>> def divide_large_ints(n, div):
>            x = divmod(n, div)
>            return str(x[0]) + str(x[1]/div).lstrip('0')
>
>
> >>> n = 2000000000000000000000000000000033
> >>> div = 2
> >>> divide_large_ints(n, div)
> '1000000000000000000000000000000016.5'
> >>>
>
> Dick
>
>
> ------------------------------
>
> Message: 6
> Date: Thu, 1 Jul 2010 20:57:53 -0700
> From: "Richard D. Moores" <rdmoores at gmail.com>
> To: Alan Gauld <alan.gauld at btinternet.com>
> Cc: tutor at python.org
> Subject: Re: [Tutor] (no subject)
> Message-ID:
>        <AANLkTik0umnTHzg4-luIytzPLT36g1rG-If2rt1G63XE at mail.gmail.com>
> Content-Type: text/plain; charset=UTF-8
>
> On Wed, Jun 30, 2010 at 12:33, Alan Gauld <alan.gauld at btinternet.com>
> wrote:
> >
> > "Aaron Chambers" <a.pringles.can at gmail.com> wrote in message
> > news:AANLkTinH0PTFxhSbQrwiUjML8NMuzCDcpQxScIRhct35 at mail.gmail.com...
> >>
> >> I'm new to Python, and wanted to start messing around with it, but the
> >> computer I'm using is running Windows 7, so is there a version of Python
> >> that's compatible with 7?
> >
> > Yes, and I would recommend you get yours from the Activestate.com
> > web site rather than python.org since the Activestate version is much
> > more Windows friendly.
>
> Alan, I'm interested. Could you tell us more about how it's more
> Windows friendly?
>
> BTW I just tried to install ActivePython 3.1.2.3 (Win 64-bit x64), and
> waited more than 10 minutes while the installation program checked on
> space on my laptop. I used Task Manager to stop it. Will try again
> later.
>
> Dick
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 77, Issue 3
> ************************************
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100702/b057f589/attachment-0001.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: HANGMAN.py
Type: application/octet-stream
Size: 2255 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100702/b057f589/attachment-0001.obj>

From steve at pearwood.info  Fri Jul  2 18:09:40 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 3 Jul 2010 02:09:40 +1000
Subject: [Tutor] Tutor Digest, Vol 77, Issue 3
In-Reply-To: <AANLkTil7GGlRSJ8vg9yMoz4KNAn19_VHmD-PUBSomDed@mail.gmail.com>
References: <mailman.414.1278043095.1671.tutor@python.org>
	<AANLkTil7GGlRSJ8vg9yMoz4KNAn19_VHmD-PUBSomDed@mail.gmail.com>
Message-ID: <201007030209.41080.steve@pearwood.info>

On Sat, 3 Jul 2010 01:44:26 am Jacob Bender wrote:
> Instead of using "find" you could use a for loop. Explore what I mean
> in the attachment. If you have IDLE you can look at the programming
> in it.

Jacob, please trim your replies, *especially* when replying to a digest. 
There is absolutely no reason to include over 400 lines of quoted text, 
from multiple posts, just to add a two sentence comment.

And as the digest itself says:

> > When replying, please edit your Subject line so it is more specific
> > than "Re: Contents of Tutor digest..."

And one last comment... your attachment (HANGMAN.py) is severely broken. 
For some reason it is base-64 encoded, which shouldn't be necessary for 
a plain-text file, and furthermore it doesn't decode in my mail client.


-- 
Steven D'Aprano

From smokefloat at gmail.com  Fri Jul  2 18:57:28 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 2 Jul 2010 12:57:28 -0400
Subject: [Tutor] Reading a file
In-Reply-To: <201007030131.22700.steve@pearwood.info>
References: <AANLkTil4QjpbnlVpnRsDMhStqAx_xdxEAemnFI3Tnb1w@mail.gmail.com>
	<201007030131.22700.steve@pearwood.info>
Message-ID: <AANLkTinTbwXTO2uX-gvyuJIhFfOGiROUuykTUeYWYT1k@mail.gmail.com>

On Fri, Jul 2, 2010 at 11:31 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Fri, 2 Jul 2010 11:16:02 pm David Hutto wrote:
>> In the code below, I'm trying to read from a file, and print out the
>> lines.
>
> f = open("filename.txt")
> for line in f:
> ? ?print line
> f.close()
>
> is all you need, and even the close at the end is optional (but
> recommended).
>
>
>> I know I've seen the exact function I'm looking for here, but
>> it seems like the below 'should' work.
>>
>> The second function(rdfil) works, if just the line number is placed
>> there, and th first(increment) works for printing a new number in
>> range for the rdfil to operate while going through the lines in the
>> file.
>> Any other options other than using linecache.getline(I'm sure there
>> are, just haven't jogged the right memory cell loose yet)?
>>
>> def increment():
>> ? ? ? for number in range(1, 500):
>> ? ? ? ? ? ? ? print number ++1
>
> Why do you have number ++1 instead of just number+1 ?
>
> For that matter, why do you have number+1 instead of changing the range
> to range(2, 501)?

I was 'thinking' that since it worked in the interpreter as printing
the numbers 1-500 , it would cycle through to the linecache.getline's
number of line variable that it calls when it went back through each
time. It might be better explained as to what I thought it was doing.

>
>
>> def rdfil():
>> ? ? ? outputfile = raw_input('Input file name: ')
>
> This puts a *string* in the variable outputfile. A better name would
> be "outputfilename", because it is a file NAME, not a file.
>
>> ? ? ? for line in outputfile:
>
> This is terribly misleading, because iterating over a string gives you
> the individual characters of the string, not lines. E.g.:>
> for line in "file.txt":
> ? ?print line
>
> will print:
>
> f
> i
> l
> e
> .
> t
> x
> t
>
>> ? ? ? ? ? ? ? if line:
>
> This will always be true, and so is pointless. Even an empty line is not
> truly empty, as it will be a newline character. When the file is empty,
> the for-loop will exit.

This what I thought would happen for the each line, and it would only
loop through until it hit a 'non-assigned' line, which would stop the
call of the for range function, and stop telling the getline to spit
out a new number in range.

Here is where using the above worked and why I added it to the function:

david at david-laptop:~/Documents/inprogress/projectsmain/Python Projects$ python
Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import linecache
>>> readcont = linecache.getline('/home/david/testmkfile.txt', 1)
>>> print readcont
abcdefghijklmnopqrstuvwxyz12345678910!@#$%^&*()_+~

>>>

the for line in was added after to the function in an app(which is
where it's being called from) , and I assumed it would go through the
file line by line like that. I could have checked the function better
before placing it to be called by the app.

>
>> ? ? ? ? ? ? ? ? ? ? ? readcont = linecache.getline(outputfile, increment) '''increment
>> is originally supposed to be an int for the line number being read'''
>
> This line gives a syntax error. What is it supposed to be? What is the
> purpose of the string? It looks like it is meant to be a comment, but
> why have you written it as a string instead of a # comment?

I started with the #, it was added at the time of the email to explain
why the variable was there and not a numerical line number. At the
last second I added it because I thought if you copied and pasted it,
it would consume more than a one line comment for the person copying
due to the wordwrap.

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


Thanks, for the memory jog, and snippet though.

David

From alan.gauld at btinternet.com  Fri Jul  2 20:27:50 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 2 Jul 2010 19:27:50 +0100
Subject: [Tutor] Reading a file
References: <AANLkTil4QjpbnlVpnRsDMhStqAx_xdxEAemnFI3Tnb1w@mail.gmail.com>
Message-ID: <i0lb35$h23$1@dough.gmane.org>


"David Hutto" <smokefloat at gmail.com> wrote

> In the code below, I'm trying to read from a file, and print out the 
> lines.

Steven addressed that but...

> def increment():
>      for number in range(1, 500):
>          print number ++1

This function if called will print out all of the numbers at once, it 
won't return anything.
I don't think thats what you want. Maybe it was:

def increment()
     for number in range(500)
          yield number + 1       # returns the numbers 1.....500, one 
number per call.

There are better ways to do that but this was the nearest guess
I could make to your possible intent...

> readcont = linecache.getline(outputfile, increment) '''increment is

Here you pass the name of the function increment, I suspect
that you meant to do

readcont = linecache.getline(outputfile, increment() )

where increment was like the generator function above.

However even if you did want to do that using enumerate() would
probably be more effective. So slightly mofdifying Steven's code:

f = open("filename.txt")
for number, line in enumerate(f):
    print "%5d%s" % (number, line)
f.close()


Is that close?


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




From filtera at gmail.com  Fri Jul  2 20:40:49 2010
From: filtera at gmail.com (Chris C.)
Date: Fri, 2 Jul 2010 13:40:49 -0500
Subject: [Tutor] Help with choices for new database program
Message-ID: <001501cb1a16$1a1a8760$4e4f9620$@com>

Hi,

I'm not a programmer, but I have been exposed to some programming basics.
I've written small parts of console-based C++ programs in an OOP class I
took last year (but nothing outside of the classroom setting), and on my own
I've written some semi-simple multi-form multi-report databases in Access,
including the event-based VBA behind the scenes in those dbs.

 

I'm writing this question because I want, for my own satisfaction, to
rewrite one of my Access dbs (one that does our finances) into a stand-alone
Python database program using SQLite.  I know I'll be learning as I go, but
that'll work, I'm not in a big hurry and I'll work on it in my spare time.
Right now I'm trying to get organized and get a game plan, and that's where
I need help.  

 

I need to ask experienced people to help me make decisions on what tools I
should use.  As I said, I'm pretty set on Python and Sqlite.  I believe I
want to use an ORM so I'm thinking I'll use SQL Alchemy (it seems to be the
biggy out there, and I'm sure I will need lots of documentation, and forum
help too).  I've read that Eclipse with PyDev is a good IDE, so I thought
I'd use them.  I've also read that wxGlade will help me easily design a gui
(drag and drop style), and that it will generate the code for my UI so that
I just have to bind to it with my business logic code.  How should I do my
reports?  I like Access's report style (since they are formatted already for
printing), but I'm open to other styles too.  

 

Am I understanding what these things are and what they do?  If not, can you
help me understand how all these pieces fit together and what function they
each have toward writing my program?

What else will I need?

What products (free ones please) can you recommend for me to use?

 

(Ease of learning and speed to a finished program are what I'm mainly
looking for.  I'm really only looking to learn the skills I need for this
particular project, and not to gain a broad development skill set.  My
professional field is not computer related and this project only for my
personal satisfaction.)

 

Sorry this message was so long.  Thanks one and all for your help!

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100702/d875337e/attachment.html>

From jeff at dcsoftware.com  Fri Jul  2 23:55:24 2010
From: jeff at dcsoftware.com (Jeff Johnson)
Date: Fri, 02 Jul 2010 14:55:24 -0700
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <001501cb1a16$1a1a8760$4e4f9620$@com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
Message-ID: <4C2E604C.6030608@dcsoftware.com>

On 07/02/2010 11:40 AM, Chris C. wrote: I'm writing this question 
because I want, for my own satisfaction, to rewrite one of my Access dbs 
(one that does our finances) into a stand-alone Python database program 
using SQLite.  I know I'll be learning as I go, but that'll work, I'm 
not in a big hurry and I'll work on it in my spare time.  Right now I'm 
trying to get organized and get a game plan, and that's where I need help.

I have been developing database applications for 20 years using FoxPro 
and VFP.  Now I am developing using Dabo.  Dabo is a framework wrapper 
for wxPython written totally in Python.  I use SQLite for small 
applications and PostgreSQL for larger ones.  Dabo was written by two of 
the top FoxPro developers and is supported by many others all over the 
world.

http://dabodev.com/

Please check it out.  And go to www.leafe.com and subscribe to the 
dabo-user email list.

-- 

Jeff

-------------------

Jeff Johnson
jeff at dcsoftware.com


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100702/017243d9/attachment-0001.html>

From rdmoores at gmail.com  Sat Jul  3 00:59:48 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Fri, 2 Jul 2010 15:59:48 -0700
Subject: [Tutor] (no subject)
In-Reply-To: <1278072114.4865.1382981917@webmail.messagingengine.com>
References: <AANLkTinH0PTFxhSbQrwiUjML8NMuzCDcpQxScIRhct35@mail.gmail.com> 
	<i0g666$o8$1@dough.gmane.org>
	<AANLkTik0umnTHzg4-luIytzPLT36g1rG-If2rt1G63XE@mail.gmail.com> 
	<1278072114.4865.1382981917@webmail.messagingengine.com>
Message-ID: <AANLkTilC-DPUa2e5Zi8A7SypnzOp9sUNE17DOXHozKU0@mail.gmail.com>

On Fri, Jul 2, 2010 at 05:01, Malcolm Greene <mgreene at bdurham.com> wrote:
> Hi Richard,
>
> I've used Activestate's Python setups in the past with success.
>
> But I recently had a problem with their setups running under Windows 7
> (64-bit). I can't remember the specific problem, but after much head
> scratching and frustration, decided to go back and use the official
> Python distribution which worked fine.
>
> I did have to install the Win 32 extensions myself which is easy - they
> come packaged as a Windows setup utility.

I posted on an ActiveState forum
(<http://community.activestate.com/forum/installation-stalls#comments>)
and got an answer that enabled me to install ActivePython 3.1.2 .
Everything looks great so far.

Dick
(On 64-bit Vista; Still preparing for 64-bit Win 7)

From alan.gauld at btinternet.com  Sat Jul  3 01:40:20 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 3 Jul 2010 00:40:20 +0100
Subject: [Tutor] Help with choices for new database program
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
Message-ID: <i0ltd3$61k$1@dough.gmane.org>


"Chris C." <filtera at gmail.com> wrote

> rewrite one of my Access dbs (one that does our finances) into a 
> stand-alone
> Python database program using SQLite.  I know I'll be learning as I 
> go, but
> that'll work, I'm not in a big hurry and I'll work on it in my spare 
> time.

If its a database focused app I'd take a look at Dabo.
It has a GUI builder but also has links to database tables etc.

http://dabodev.com/

I've only played with it briefly (followed the tutorial) since I don't 
do much
database work in Python but it did look like a good tool for data 
centric
desktop GUI based apps.

HTH,


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



From jeff at dcsoftware.com  Sat Jul  3 02:56:07 2010
From: jeff at dcsoftware.com (Jeff Johnson)
Date: Fri, 02 Jul 2010 17:56:07 -0700
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <001f01cb1a47$b50eb030$1f2c1090$@com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
	<4C2E395E.4010101@dcsoftware.com>
	<001f01cb1a47$b50eb030$1f2c1090$@com>
Message-ID: <4C2E8AA7.4000109@dcsoftware.com>

On 07/02/2010 05:35 PM, Chris C. wrote:
>
> Hi Jeff, thank for your reply!  I'm aware of Dabo and was pretty much 
> sold on using it until the last couple of days.  I was trying to 
> install it so I could start connecting to my tables when I ran into a 
> problem with the instructions for installing ReportLab.  I wrote to 
> the mailing list Wednesday but haven't heard from anyone.  Being such 
> a  beginner and knowing I'll be needing help, it kind of has me wary 
> of committing to Dabo when I'm having this trouble getting help before 
> I even get started.  I saw your post to the Dabo mailing list with the 
> title "Reference to bizjob control" has been getting responses.  Can 
> you confirm whether my question went out to the list recipients?  Did 
> you receive it?
>
> Like I was saying, I wanted to use Dabo, but I submitted this question 
> to this board because I was beginning to lose faith in being able to 
> get help from the Dabo mailing list.
>
> Thanks again,
>
> Chris C.
>
> *From:* Jeff Johnson [mailto:jeff at dcsoftware.com]
> *Sent:* Friday, July 02, 2010 2:09 PM
> *To:* Chris C.
> *Subject:* Re: [Tutor] Help with choices for new database program
>
> On 07/02/2010 11:40 AM, Chris C. wrote: I'm writing this question 
> because I want, for my own satisfaction, to rewrite one of my Access 
> dbs (one that does our finances) into a stand-alone Python database 
> program using SQLite.  I know I'll be learning as I go, but that'll 
> work, I'm not in a big hurry and I'll work on it in my spare time.  
> Right now I'm trying to get organized and get a game plan, and that's 
> where I need help.
>
> I have been developing database applications for 20 years using FoxPro 
> and VFP.  Now I am developing using Dabo.  Dabo is a framework wrapper 
> for wxPython written totally in Python.  I use SQLite for small 
> applications and PostgreSQL for larger ones.  Dabo was written by two 
> of the top FoxPro developers and is supported by many others all over 
> the world.
>
> http://dabodev.com/
>
> Please check it out.  And go to www.leafe.com <http://www.leafe.com> 
> and subscribe to the dabo-user email list.
>
> -- 
>
> Jeff
>   
> -------------------
>   
> Jeff Johnson
> jeff at dcsoftware.com  <mailto:jeff at dcsoftware.com>
>   

Chris:  The folks on the Dabo list are always available for answers.  Ed 
and Paul (Dabo's developers) are always quick to answer questions and I 
guarantee they respond quicker than most lists.  There are many others 
that develop commercial applications with Dabo that are always 
monitoring the list (just like me only more experienced with Dabo and 
Python).  If you are interested please subscribe to the list:

http://www.leafe.com/mailman/listinfo/dabo-users

I did not see your post on the list so no one else did either.  If you 
developed an app using Access than you are a perfect candidate for Dabo 
and you have at least enough understanding of what is going on to use it.

There are four things that need installing in order to use Dabo.  It may 
not go as smooth as a Windows Installshield application, but you can get 
plenty of help and once it is installed you can follow the great screen 
casts and tutorials.  The users of Dabo are developing applications for 
users.  Once you have your application developed there are ways to 
package it based on your platform.

You need Python, wxPython, Dabo, and Report Lab.  You can install PIL if 
you want to manipulate images.  If you need help, just ask!

Many of the people using Dabo are moving over from Visual FoxPro which 
is very similar to Access, so don't be afraid to ask any question.  If 
you ask a question the question and answer will be saved in the archives 
for others to learn.

Come on in, the water is fine!

-- 
Jeff

---------------

Jeff Johnson
jeff at san-dc.com
(623) 582-0323

www.san-dc.com


-- 
Jeff

-------------------

Jeff Johnson
jeff at dcsoftware.com



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100702/de61efd3/attachment.html>

From smokefloat at gmail.com  Sat Jul  3 03:14:58 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 2 Jul 2010 21:14:58 -0400
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <4C2E8AA7.4000109@dcsoftware.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
	<4C2E395E.4010101@dcsoftware.com>
	<001f01cb1a47$b50eb030$1f2c1090$@com>
	<4C2E8AA7.4000109@dcsoftware.com>
Message-ID: <AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>

On Fri, Jul 2, 2010 at 8:56 PM, Jeff Johnson <jeff at dcsoftware.com> wrote:
> On 07/02/2010 05:35 PM, Chris C. wrote:
>
> Hi Jeff, thank for your reply!? I?m aware of Dabo and was pretty much sold
> on using it until the last couple of days.? I was trying to install it so I
> could start connecting to my tables when I ran into a problem with the
> instructions for installing ReportLab.? I wrote to the mailing list
> Wednesday but haven?t heard from anyone.? Being such a? beginner and knowing
> I?ll be needing help, it kind of has me wary of committing to Dabo when I?m
> having this trouble getting help before I even get started.? I saw your post
> to the Dabo mailing list with the title ?Reference to bizjob control? has
> been getting responses.? Can you confirm whether my question went out to the
> list recipients?? Did you receive it?

Stick to the main python libraries(python with sqllite, and for the
standalone exe know it's somewhere, and I've seen it in the past few
days, but didn't pay attention because it wasn't important to what I
was doing at the time) going anywhere else is the beginning of an ADHD
nightmare. It's like being a hypochondriac with an unlimited
healthcare plan, you'll want to see any option except for the obvious
in front of you.

Try not to get distracted by the shiny things unless necessary.

>
>
>
> Like I was saying, I wanted to use Dabo, but I submitted this question to
> this board because I was beginning to lose faith in being able to get help
> from the Dabo mailing list.
>
>
>
> Thanks again,
>
> Chris C.
>
>
>
>
>
> From: Jeff Johnson [mailto:jeff at dcsoftware.com]
> Sent: Friday, July 02, 2010 2:09 PM
> To: Chris C.
> Subject: Re: [Tutor] Help with choices for new database program
>
>
>
> On 07/02/2010 11:40 AM, Chris C. wrote: I?m writing this question because I
> want, for my own satisfaction, to rewrite one of my Access dbs (one that
> does our finances) into a stand-alone Python database program using SQLite.
> I know I?ll be learning as I go, but that?ll work, I?m not in a big hurry
> and I?ll work on it in my spare time.? Right now I?m trying to get organized
> and get a game plan, and that?s where I need help.
>
> I have been developing database applications for 20 years using FoxPro and
> VFP.? Now I am developing using Dabo.? Dabo is a framework wrapper for
> wxPython written totally in Python.? I use SQLite for small applications and
> PostgreSQL for larger ones.? Dabo was written by two of the top FoxPro
> developers and is supported by many others all over the world.
>
> http://dabodev.com/
>
> Please check it out.? And go to www.leafe.com and subscribe to the dabo-user
> email list.
>
> --
>
> Jeff
>
>
>
> -------------------
>
>
>
> Jeff Johnson
>
> jeff at dcsoftware.com
>
>
>
> Chris:? The folks on the Dabo list are always available for answers.? Ed and
> Paul (Dabo's developers) are always quick to answer questions and I
> guarantee they respond quicker than most lists.? There are many others that
> develop commercial applications with Dabo that are always monitoring the
> list (just like me only more experienced with Dabo and Python).? If you are
> interested please subscribe to the list:
>
> http://www.leafe.com/mailman/listinfo/dabo-users
>
> I did not see your post on the list so no one else did either.? If you
> developed an app using Access than you are a perfect candidate for Dabo and
> you have at least enough understanding of what is going on to use it.
>
> There are four things that need installing in order to use Dabo.? It may not
> go as smooth as a Windows Installshield application, but you can get plenty
> of help and once it is installed you can follow the great screen casts and
> tutorials.? The users of Dabo are developing applications for users.? Once
> you have your application developed there are ways to package it based on
> your platform.
>
> You need Python, wxPython, Dabo, and Report Lab.? You can install PIL if you
> want to manipulate images.? If you need help, just ask!
>
> Many of the people using Dabo are moving over from Visual FoxPro which is
> very similar to Access, so don't be afraid to ask any question.? If you ask
> a question the question and answer will be saved in the archives for others
> to learn.
>
> Come on in, the water is fine!
>
> --
> Jeff
>
> ---------------
>
> Jeff Johnson
> jeff at san-dc.com
> (623) 582-0323
>
> www.san-dc.com
>
> --
> Jeff
>
> -------------------
>
> Jeff Johnson
> jeff at dcsoftware.com
>
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

From jeff at dcsoftware.com  Sat Jul  3 03:30:01 2010
From: jeff at dcsoftware.com (Jeff Johnson)
Date: Fri, 02 Jul 2010 18:30:01 -0700
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>	<4C2E395E.4010101@dcsoftware.com>	<001f01cb1a47$b50eb030$1f2c1090$@com>	<4C2E8AA7.4000109@dcsoftware.com>
	<AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>
Message-ID: <4C2E9299.2040605@dcsoftware.com>

On 07/02/2010 06:14 PM, David Hutto wrote:
>
> Stick to the main python libraries(python with sqllite, and for the
> standalone exe know it's somewhere, and I've seen it in the past few
> days, but didn't pay attention because it wasn't important to what I
> was doing at the time) going anywhere else is the beginning of an ADHD
> nightmare. It's like being a hypochondriac with an unlimited
> healthcare plan, you'll want to see any option except for the obvious
> in front of you.
>
> Try not to get distracted by the shiny things unless necessary.
>
>
I'm not sure how this helps with Chris's application.  I will agree that 
the number of choices is daunting!  The nice thing about Dabo is the 
group is focused on database applications.  Kind of like Django is 
focused on web devopment.

I mean this in a joking way:  If you find that Python and open source 
creates too many decisions then you can consider Microsoft .NET and 
Microsoft SQL Server on Windows 7.

I am a recovering Microsoft developer of over 20 years.  ;^)

BTW learning Python is awesome!

-- 
Jeff

-------------------

Jeff Johnson
jeff at dcsoftware.com



From smokefloat at gmail.com  Sat Jul  3 03:31:42 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 2 Jul 2010 21:31:42 -0400
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <4C2E9219.4090805@san-dc.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
	<4C2E395E.4010101@dcsoftware.com>
	<001f01cb1a47$b50eb030$1f2c1090$@com>
	<4C2E8AA7.4000109@dcsoftware.com>
	<AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>
	<4C2E9219.4090805@san-dc.com>
Message-ID: <AANLkTin-b0HlmdL9rdXNnALHko8UaYOllam2VU1Z22Tn@mail.gmail.com>

On Fri, Jul 2, 2010 at 9:27 PM, Jeff Johnson <jeff at san-dc.com> wrote:
> On 07/02/2010 06:14 PM, David Hutto wrote:
>>
>> Stick to the main python libraries(python with sqllite, and for the
>> standalone exe know it's somewhere, and I've seen it in the past few
>> days, but didn't pay attention because it wasn't important to what I
>> was doing at the time) going anywhere else is the beginning of an ADHD
>> nightmare. It's like being a hypochondriac with an unlimited
>> healthcare plan, you'll want to see any option except for the obvious
>> in front of you.
>>
>> Try not to get distracted by the shiny things unless necessary.
>>
>
> I'm not sure how this helps with Chris's application. ?I will agree that the
> number of choices is daunting! ?The nice thing about Dabo is the group is
> focused on database applications. ?Kind of like Django is focused on web
> devopment.

Well, it was mainly that he said he was a beginner and was only using
this for a single banking project, I do believe.

Not that learning a new package would be helpful, I like
experimenting, and failing/succeeding, but if this is all he needs to
accomplish, then not using more than is necessary would be beneficial.
A simple script, with simple sqlite fields to maintain.

>
> I mean this in a joking way: ?If you find that Python and open source
> creates too many decisions then you can consider Microsoft .NET and
> Microsoft SQL Server on Windows 7.
>
> I am a recovering Microsoft developer of over 20 years. ?;^)
>
> BTW learning Python is awesome!
>
> --
>
> Jeff
>
> ---------------
>
> Jeff Johnson
> jeff at san-dc.com
> (623) 582-0323
>
> www.san-dc.com
>
>

From smokefloat at gmail.com  Sat Jul  3 03:32:21 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 2 Jul 2010 21:32:21 -0400
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <AANLkTin-b0HlmdL9rdXNnALHko8UaYOllam2VU1Z22Tn@mail.gmail.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
	<4C2E395E.4010101@dcsoftware.com>
	<001f01cb1a47$b50eb030$1f2c1090$@com>
	<4C2E8AA7.4000109@dcsoftware.com>
	<AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>
	<4C2E9219.4090805@san-dc.com>
	<AANLkTin-b0HlmdL9rdXNnALHko8UaYOllam2VU1Z22Tn@mail.gmail.com>
Message-ID: <AANLkTinvamCgOWzvm1by38hpOU8xOB2KE9rsHpC5u9VD@mail.gmail.com>

On Fri, Jul 2, 2010 at 9:31 PM, David Hutto <smokefloat at gmail.com> wrote:
> On Fri, Jul 2, 2010 at 9:27 PM, Jeff Johnson <jeff at san-dc.com> wrote:
>> On 07/02/2010 06:14 PM, David Hutto wrote:
>>>
>>> Stick to the main python libraries(python with sqllite, and for the
>>> standalone exe know it's somewhere, and I've seen it in the past few
>>> days, but didn't pay attention because it wasn't important to what I
>>> was doing at the time) going anywhere else is the beginning of an ADHD
>>> nightmare. It's like being a hypochondriac with an unlimited
>>> healthcare plan, you'll want to see any option except for the obvious
>>> in front of you.
>>>
>>> Try not to get distracted by the shiny things unless necessary.
>>>
>>
>> I'm not sure how this helps with Chris's application. ?I will agree that the
>> number of choices is daunting! ?The nice thing about Dabo is the group is
>> focused on database applications. ?Kind of like Django is focused on web
>> devopment.
>
> Well, it was mainly that he said he was a beginner and was only using
> this for a single banking project, I do believe.
>
> Not that learning a new package would

wouldn't


 be helpful, I like
> experimenting, and failing/succeeding, but if this is all he needs to
> accomplish, then not using more than is necessary would be beneficial.
> A simple script, with simple sqlite fields to maintain.
>
>>
>> I mean this in a joking way: ?If you find that Python and open source
>> creates too many decisions then you can consider Microsoft .NET and
>> Microsoft SQL Server on Windows 7.
>>
>> I am a recovering Microsoft developer of over 20 years. ?;^)
>>
>> BTW learning Python is awesome!
>>
>> --
>>
>> Jeff
>>
>> ---------------
>>
>> Jeff Johnson
>> jeff at san-dc.com
>> (623) 582-0323
>>
>> www.san-dc.com
>>
>>
>

From smokefloat at gmail.com  Sat Jul  3 03:51:24 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 2 Jul 2010 21:51:24 -0400
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <4C2E9610.6010307@san-dc.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
	<4C2E395E.4010101@dcsoftware.com>
	<001f01cb1a47$b50eb030$1f2c1090$@com>
	<4C2E8AA7.4000109@dcsoftware.com>
	<AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>
	<4C2E9219.4090805@san-dc.com>
	<AANLkTin-b0HlmdL9rdXNnALHko8UaYOllam2VU1Z22Tn@mail.gmail.com>
	<AANLkTinvamCgOWzvm1by38hpOU8xOB2KE9rsHpC5u9VD@mail.gmail.com>
	<4C2E9610.6010307@san-dc.com>
Message-ID: <AANLkTimP74mVLRPV051nvW9KJ6OqXcGBYUkryXKmiewe@mail.gmail.com>

On Fri, Jul 2, 2010 at 9:44 PM, Jeff Johnson <jeff at san-dc.com> wrote:
> On 07/02/2010 06:32 PM, David Hutto wrote:
>>
>> On Fri, Jul 2, 2010 at 9:31 PM, David Hutto<smokefloat at gmail.com> ?wrote:
>>
>>>
>>> Well, it was mainly that he said he was a beginner and was only using
>>> this for a single banking project, I do believe.
>>>
>>> Not that learning a new package would
>>
>> wouldn't
>>
>>
>> ?be helpful, I like
>>
>>>
>>> experimenting, and failing/succeeding, but if this is all he needs to
>>> accomplish, then not using more than is necessary would be beneficial.
>>> A simple script, with simple sqlite fields to maintain.
>>>
>>>
>
> David: ?Experimenting, failing and succeeding is the life of a programmer.
> ?I have been programming for many years in assemply, FORTRAN, COBOL, Basic,
> RPG, FoxPro, C, but I am now totally committed to Python. ?It is the best of
> all worlds. ?Coming from the Microsoft side, open source and Python creates
> a whole new set of problems. ?Do I use Windows? ?Do I use Linux? ?Do I use
> my Mac Book Pro? ?You do have to make some decisions before moving on. ?The
> choices are endless.
>
> I have found Dabo and Django to be beneficial for me because they target
> what I want to do.
>
> Your mileage may vary. ?;^)


In the end, there might be so many packages, I might not be able to
handle it all(for my own uses). But, I would think, you would agree
that a simple account balance app, would be no more than tkinter with
a few functions to write and retrieve data from a sqlite db. To quote
Sherlock, 'Sometimes, after eliminating the impossible, what ever is
left, no matter how improbable, must be the solution.', or something
like that.


>
> --
> Jeff
>
> ---------------
>
> Jeff Johnson
> jeff at san-dc.com
> (623) 582-0323
>
> www.san-dc.com
>
>

From jeff at dcsoftware.com  Sat Jul  3 03:55:38 2010
From: jeff at dcsoftware.com (Jeff Johnson)
Date: Fri, 02 Jul 2010 18:55:38 -0700
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <AANLkTimP74mVLRPV051nvW9KJ6OqXcGBYUkryXKmiewe@mail.gmail.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>	<4C2E395E.4010101@dcsoftware.com>	<001f01cb1a47$b50eb030$1f2c1090$@com>	<4C2E8AA7.4000109@dcsoftware.com>	<AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>	<4C2E9219.4090805@san-dc.com>	<AANLkTin-b0HlmdL9rdXNnALHko8UaYOllam2VU1Z22Tn@mail.gmail.com>	<AANLkTinvamCgOWzvm1by38hpOU8xOB2KE9rsHpC5u9VD@mail.gmail.com>	<4C2E9610.6010307@san-dc.com>
	<AANLkTimP74mVLRPV051nvW9KJ6OqXcGBYUkryXKmiewe@mail.gmail.com>
Message-ID: <4C2E989A.6070300@dcsoftware.com>

On 07/02/2010 06:51 PM, David Hutto wrote:
> In the end, there might be so many packages, I might not be able to
> handle it all(for my own uses). But, I would think, you would agree
> that a simple account balance app, would be no more than tkinter with
> a few functions to write and retrieve data from a sqlite db. To quote
> Sherlock, 'Sometimes, after eliminating the impossible, what ever is
> left, no matter how improbable, must be the solution.', or something
> like that.
>

David:  I like your quote!  I am a huge Sherlock Holmes fan.  I like 
Dabo because I develop commercial applications.

-- 
Jeff

-------------------

Jeff Johnson
jeff at dcsoftware.com



From smokefloat at gmail.com  Sat Jul  3 04:01:12 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 2 Jul 2010 22:01:12 -0400
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <4C2E989A.6070300@dcsoftware.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
	<4C2E395E.4010101@dcsoftware.com>
	<001f01cb1a47$b50eb030$1f2c1090$@com>
	<4C2E8AA7.4000109@dcsoftware.com>
	<AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>
	<4C2E9219.4090805@san-dc.com>
	<AANLkTin-b0HlmdL9rdXNnALHko8UaYOllam2VU1Z22Tn@mail.gmail.com>
	<AANLkTinvamCgOWzvm1by38hpOU8xOB2KE9rsHpC5u9VD@mail.gmail.com>
	<4C2E9610.6010307@san-dc.com>
	<AANLkTimP74mVLRPV051nvW9KJ6OqXcGBYUkryXKmiewe@mail.gmail.com>
	<4C2E989A.6070300@dcsoftware.com>
Message-ID: <AANLkTilqNklWLV1mFPoTHQa9N7qT3mIW40IgfS-x4DHk@mail.gmail.com>

On Fri, Jul 2, 2010 at 9:55 PM, Jeff Johnson <jeff at dcsoftware.com> wrote:
> On 07/02/2010 06:51 PM, David Hutto wrote:
>>
>> In the end, there might be so many packages, I might not be able to
>> handle it all(for my own uses). But, I would think, you would agree
>> that a simple account balance app, would be no more than tkinter with
>> a few functions to write and retrieve data from a sqlite db. To quote
>> Sherlock, 'Sometimes, after eliminating the impossible, what ever is
>> left, no matter how improbable, must be the solution.', or something
>> like that.
>>
>
> David: ?I like your quote! ?I am a huge Sherlock Holmes fan. ?I like Dabo
> because I develop commercial applications.

'I love to develop relatively operational residential programs that
quasi-suit my own purpose', I said sarcastically. 'So hopefully I'll
join the commercial, then industrial one day', I said optimistically,
looking pessimistically up at the sky, while lazily, daydreaming
blurred images of the future.

>
> --
> Jeff
>
> -------------------
>
> Jeff Johnson
> jeff at dcsoftware.com
>
>
>

From smokefloat at gmail.com  Sat Jul  3 04:07:26 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 2 Jul 2010 22:07:26 -0400
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <AANLkTilqNklWLV1mFPoTHQa9N7qT3mIW40IgfS-x4DHk@mail.gmail.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
	<4C2E395E.4010101@dcsoftware.com>
	<001f01cb1a47$b50eb030$1f2c1090$@com>
	<4C2E8AA7.4000109@dcsoftware.com>
	<AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>
	<4C2E9219.4090805@san-dc.com>
	<AANLkTin-b0HlmdL9rdXNnALHko8UaYOllam2VU1Z22Tn@mail.gmail.com>
	<AANLkTinvamCgOWzvm1by38hpOU8xOB2KE9rsHpC5u9VD@mail.gmail.com>
	<4C2E9610.6010307@san-dc.com>
	<AANLkTimP74mVLRPV051nvW9KJ6OqXcGBYUkryXKmiewe@mail.gmail.com>
	<4C2E989A.6070300@dcsoftware.com>
	<AANLkTilqNklWLV1mFPoTHQa9N7qT3mIW40IgfS-x4DHk@mail.gmail.com>
Message-ID: <AANLkTimctqhmuHbSReCTuZ1xYeMj-BKIxsjVtdVWq0eE@mail.gmail.com>

On Fri, Jul 2, 2010 at 10:01 PM, David Hutto <smokefloat at gmail.com> wrote:
> On Fri, Jul 2, 2010 at 9:55 PM, Jeff Johnson <jeff at dcsoftware.com> wrote:
>> On 07/02/2010 06:51 PM, David Hutto wrote:
>>>
>>> In the end, there might be so many packages, I might not be able to
>>> handle it all(for my own uses). But, I would think, you would agree
>>> that a simple account balance app, would be no more than tkinter with
>>> a few functions to write and retrieve data from a sqlite db. To quote
>>> Sherlock, 'Sometimes, after eliminating the impossible, what ever is
>>> left, no matter how improbable, must be the solution.', or something
>>> like that.
>>>
>>
>> David: ?I like your quote! ?I am a huge Sherlock Holmes fan. ?I like Dabo
>> because I develop commercial applications.
>
> 'I love to develop relatively operational residential programs that
> quasi-suit my own purpose', I said sarcastically. 'So hopefully I'll
> join the commercial, then industrial one day', I said optimistically,
> looking pessimistically up at the sky, while lazily, daydreaming
> blurred images of the future.
>
>>
>> --
>> Jeff
>>
>> -------------------
>>
>> Jeff Johnson
>> jeff at dcsoftware.com
>>
>>
>>
>

But...maybe actually accessing the bank account url and logging in,
then checking, might be made easier by those you suggested. What would
be the ultimate intent of the developer of the app?

From smokefloat at gmail.com  Sat Jul  3 04:10:00 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 2 Jul 2010 22:10:00 -0400
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <AANLkTimctqhmuHbSReCTuZ1xYeMj-BKIxsjVtdVWq0eE@mail.gmail.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
	<4C2E395E.4010101@dcsoftware.com>
	<001f01cb1a47$b50eb030$1f2c1090$@com>
	<4C2E8AA7.4000109@dcsoftware.com>
	<AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>
	<4C2E9219.4090805@san-dc.com>
	<AANLkTin-b0HlmdL9rdXNnALHko8UaYOllam2VU1Z22Tn@mail.gmail.com>
	<AANLkTinvamCgOWzvm1by38hpOU8xOB2KE9rsHpC5u9VD@mail.gmail.com>
	<4C2E9610.6010307@san-dc.com>
	<AANLkTimP74mVLRPV051nvW9KJ6OqXcGBYUkryXKmiewe@mail.gmail.com>
	<4C2E989A.6070300@dcsoftware.com>
	<AANLkTilqNklWLV1mFPoTHQa9N7qT3mIW40IgfS-x4DHk@mail.gmail.com>
	<AANLkTimctqhmuHbSReCTuZ1xYeMj-BKIxsjVtdVWq0eE@mail.gmail.com>
Message-ID: <AANLkTilX29_NlAhNgVt3LdyWaXXSdLIMqQr3-HGgJTFn@mail.gmail.com>

On Fri, Jul 2, 2010 at 10:07 PM, David Hutto <smokefloat at gmail.com> wrote:
> On Fri, Jul 2, 2010 at 10:01 PM, David Hutto <smokefloat at gmail.com> wrote:
>> On Fri, Jul 2, 2010 at 9:55 PM, Jeff Johnson <jeff at dcsoftware.com> wrote:
>>> On 07/02/2010 06:51 PM, David Hutto wrote:
>>>>
>>>> In the end, there might be so many packages, I might not be able to
>>>> handle it all(for my own uses). But, I would think, you would agree
>>>> that a simple account balance app, would be no more than tkinter with
>>>> a few functions to write and retrieve data from a sqlite db. To quote
>>>> Sherlock, 'Sometimes, after eliminating the impossible, what ever is
>>>> left, no matter how improbable, must be the solution.', or something
>>>> like that.
>>>>
>>>
>>> David: ?I like your quote! ?I am a huge Sherlock Holmes fan. ?I like Dabo
>>> because I develop commercial applications.
>>
>> 'I love to develop relatively operational residential programs that
>> quasi-suit my own purpose', I said sarcastically. 'So hopefully I'll
>> join the commercial, then industrial one day', I said optimistically,
>> looking pessimistically up at the sky, while lazily, daydreaming
>> blurred images of the future.
>>
>>>
>>> --
>>> Jeff
>>>
>>> -------------------
>>>
>>> Jeff Johnson
>>> jeff at dcsoftware.com
>>>
>>>
>>>
>>
>
> But...maybe actually accessing the bank account url and logging in,
> then checking, might be made easier by those you suggested. What would
> be the ultimate intent of the developer of the app?
>
Or maybe more extensive, in detail documentation?

Sell me and the OP.

From smokefloat at gmail.com  Sat Jul  3 04:17:23 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 2 Jul 2010 22:17:23 -0400
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <AANLkTilX29_NlAhNgVt3LdyWaXXSdLIMqQr3-HGgJTFn@mail.gmail.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
	<4C2E395E.4010101@dcsoftware.com>
	<001f01cb1a47$b50eb030$1f2c1090$@com>
	<4C2E8AA7.4000109@dcsoftware.com>
	<AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>
	<4C2E9219.4090805@san-dc.com>
	<AANLkTin-b0HlmdL9rdXNnALHko8UaYOllam2VU1Z22Tn@mail.gmail.com>
	<AANLkTinvamCgOWzvm1by38hpOU8xOB2KE9rsHpC5u9VD@mail.gmail.com>
	<4C2E9610.6010307@san-dc.com>
	<AANLkTimP74mVLRPV051nvW9KJ6OqXcGBYUkryXKmiewe@mail.gmail.com>
	<4C2E989A.6070300@dcsoftware.com>
	<AANLkTilqNklWLV1mFPoTHQa9N7qT3mIW40IgfS-x4DHk@mail.gmail.com>
	<AANLkTimctqhmuHbSReCTuZ1xYeMj-BKIxsjVtdVWq0eE@mail.gmail.com>
	<AANLkTilX29_NlAhNgVt3LdyWaXXSdLIMqQr3-HGgJTFn@mail.gmail.com>
Message-ID: <AANLkTikwgv5fi4S-SVoW6Lbvptpb1qpcNXXB767DTdtD@mail.gmail.com>

On Fri, Jul 2, 2010 at 10:10 PM, David Hutto <smokefloat at gmail.com> wrote:
> On Fri, Jul 2, 2010 at 10:07 PM, David Hutto <smokefloat at gmail.com> wrote:
>> On Fri, Jul 2, 2010 at 10:01 PM, David Hutto <smokefloat at gmail.com> wrote:
>>> On Fri, Jul 2, 2010 at 9:55 PM, Jeff Johnson <jeff at dcsoftware.com> wrote:
>>>> On 07/02/2010 06:51 PM, David Hutto wrote:
>>>>>
>>>>> In the end, there might be so many packages, I might not be able to
>>>>> handle it all(for my own uses). But, I would think, you would agree
>>>>> that a simple account balance app, would be no more than tkinter with
>>>>> a few functions to write and retrieve data from a sqlite db. To quote
>>>>> Sherlock, 'Sometimes, after eliminating the impossible, what ever is
>>>>> left, no matter how improbable, must be the solution.', or something
>>>>> like that.
>>>>>
>>>>
>>>> David: ?I like your quote! ?I am a huge Sherlock Holmes fan. ?I like Dabo
>>>> because I develop commercial applications.
>>>
>>> 'I love to develop relatively operational residential programs that
>>> quasi-suit my own purpose', I said sarcastically. 'So hopefully I'll
>>> join the commercial, then industrial one day', I said optimistically,
>>> looking pessimistically up at the sky, while lazily, daydreaming
>>> blurred images of the future.
>>>
>>>>
>>>> --
>>>> Jeff
>>>>
>>>> -------------------
>>>>
>>>> Jeff Johnson
>>>> jeff at dcsoftware.com
>>>>
>>>>
>>>>
>>>
>>
>> But...maybe actually accessing the bank account url and logging in,
>> then checking, might be made easier by those you suggested. What would
>> be the ultimate intent of the developer of the app?
>>
> Or maybe more extensive, in detail documentation?
>
> Sell me and the OP.
>

Actually do, because I have a payment transaction app I've been
thinking about(for personal development, not intentional business
use), that would incorporate something like that for interaction with
several banking accounts from several banks/financial institutions.
So, is there anything in there that would help me and the OP by
actually logging in to the site. And I can, newbie think, about
several ways, but haven't gotten to the specifics. But it does apply,
I think to the OP's question.

From bgailer at gmail.com  Sat Jul  3 05:19:24 2010
From: bgailer at gmail.com (bob gailer)
Date: Fri, 02 Jul 2010 20:19:24 -0700
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <4C2E8AA7.4000109@dcsoftware.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>	<4C2E395E.4010101@dcsoftware.com>	<001f01cb1a47$b50eb030$1f2c1090$@com>
	<4C2E8AA7.4000109@dcsoftware.com>
Message-ID: <4C2EAC3C.2000507@gmail.com>

On 7/2/2010 5:56 PM, Jeff Johnson wrote:
> [snip]

> Visual FoxPro ... is very similar to Access
>
I differ. Access and FoxPro are very different. Yes they both use 
tables, relationships, indexes and SQL. Yes they both have visual 
designers for forms and reports. Yes they both are programmable.

But the differences are much more dramatic than the commonalities. I 
have developed in both. I find it painful to work in one while desiring 
a feature that exists only in the other.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100702/f9e7070e/attachment.html>

From jeff at san-dc.com  Sat Jul  3 02:55:16 2010
From: jeff at san-dc.com (Jeff Johnson)
Date: Fri, 02 Jul 2010 17:55:16 -0700
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <001f01cb1a47$b50eb030$1f2c1090$@com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
	<4C2E395E.4010101@dcsoftware.com>
	<001f01cb1a47$b50eb030$1f2c1090$@com>
Message-ID: <4C2E8A74.2020602@san-dc.com>

On 07/02/2010 05:35 PM, Chris C. wrote:
>
> Hi Jeff, thank for your reply!  I'm aware of Dabo and was pretty much 
> sold on using it until the last couple of days.  I was trying to 
> install it so I could start connecting to my tables when I ran into a 
> problem with the instructions for installing ReportLab.  I wrote to 
> the mailing list Wednesday but haven't heard from anyone.  Being such 
> a  beginner and knowing I'll be needing help, it kind of has me wary 
> of committing to Dabo when I'm having this trouble getting help before 
> I even get started.  I saw your post to the Dabo mailing list with the 
> title "Reference to bizjob control" has been getting responses.  Can 
> you confirm whether my question went out to the list recipients?  Did 
> you receive it?
>
> Like I was saying, I wanted to use Dabo, but I submitted this question 
> to this board because I was beginning to lose faith in being able to 
> get help from the Dabo mailing list.
>
> Thanks again,
>
> Chris C.
>
> *From:* Jeff Johnson [mailto:jeff at dcsoftware.com]
> *Sent:* Friday, July 02, 2010 2:09 PM
> *To:* Chris C.
> *Subject:* Re: [Tutor] Help with choices for new database program
>
> On 07/02/2010 11:40 AM, Chris C. wrote: I'm writing this question 
> because I want, for my own satisfaction, to rewrite one of my Access 
> dbs (one that does our finances) into a stand-alone Python database 
> program using SQLite.  I know I'll be learning as I go, but that'll 
> work, I'm not in a big hurry and I'll work on it in my spare time.  
> Right now I'm trying to get organized and get a game plan, and that's 
> where I need help.
>
> I have been developing database applications for 20 years using FoxPro 
> and VFP.  Now I am developing using Dabo.  Dabo is a framework wrapper 
> for wxPython written totally in Python.  I use SQLite for small 
> applications and PostgreSQL for larger ones.  Dabo was written by two 
> of the top FoxPro developers and is supported by many others all over 
> the world.
>
> http://dabodev.com/
>
> Please check it out.  And go to www.leafe.com <http://www.leafe.com> 
> and subscribe to the dabo-user email list.
>
> -- 
>
> Jeff
>   
> -------------------
>   
> Jeff Johnson
> jeff at dcsoftware.com  <mailto:jeff at dcsoftware.com>
>   

Chris:  The folks on the Dabo list are always available for answers.  Ed 
and Paul (Dabo's developers) are always quick to answer questions and I 
guarantee they respond quicker than most lists.  There are many others 
that develop commercial applications with Dabo that are always 
monitoring the list (just like me only more experienced with Dabo and 
Python).  If you are interested please subscribe to the list:

http://www.leafe.com/mailman/listinfo/dabo-users

I did not see your post on the list so no one else did either.  If you 
developed an app using Access than you are a perfect candidate for Dabo 
and you have at least enough understanding of what is going on to use it.

There are four things that need installing in order to use Dabo.  It may 
not go as smooth as a Windows Installshield application, but you can get 
plenty of help and once it is installed you can follow the great screen 
casts and tutorials.  The users of Dabo are developing applications for 
users.  Once you have your application developed there are ways to 
package it based on your platform.

You need Python, wxPython, Dabo, and Report Lab.  You can install PIL if 
you want to manipulate images.  If you need help, just ask!

Many of the people using Dabo are moving over from Visual FoxPro which 
is very similar to Access, so don't be afraid to ask any question.  If 
you ask a question the question and answer will be saved in the archives 
for others to learn.

Come on in, the water is fine!

-- 
Jeff

---------------

Jeff Johnson
jeff at san-dc.com
(623) 582-0323

www.san-dc.com

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100702/d1f0a494/attachment.html>

From jeff at san-dc.com  Sat Jul  3 03:27:53 2010
From: jeff at san-dc.com (Jeff Johnson)
Date: Fri, 02 Jul 2010 18:27:53 -0700
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>	<4C2E395E.4010101@dcsoftware.com>	<001f01cb1a47$b50eb030$1f2c1090$@com>	<4C2E8AA7.4000109@dcsoftware.com>
	<AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>
Message-ID: <4C2E9219.4090805@san-dc.com>

On 07/02/2010 06:14 PM, David Hutto wrote:
>
> Stick to the main python libraries(python with sqllite, and for the
> standalone exe know it's somewhere, and I've seen it in the past few
> days, but didn't pay attention because it wasn't important to what I
> was doing at the time) going anywhere else is the beginning of an ADHD
> nightmare. It's like being a hypochondriac with an unlimited
> healthcare plan, you'll want to see any option except for the obvious
> in front of you.
>
> Try not to get distracted by the shiny things unless necessary.
>    
>
I'm not sure how this helps with Chris's application.  I will agree that 
the number of choices is daunting!  The nice thing about Dabo is the 
group is focused on database applications.  Kind of like Django is 
focused on web devopment.

I mean this in a joking way:  If you find that Python and open source 
creates too many decisions then you can consider Microsoft .NET and 
Microsoft SQL Server on Windows 7.

I am a recovering Microsoft developer of over 20 years.  ;^)

BTW learning Python is awesome!

-- 

Jeff

---------------

Jeff Johnson
jeff at san-dc.com
(623) 582-0323

www.san-dc.com


From jeff at san-dc.com  Sat Jul  3 03:44:48 2010
From: jeff at san-dc.com (Jeff Johnson)
Date: Fri, 02 Jul 2010 18:44:48 -0700
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <AANLkTinvamCgOWzvm1by38hpOU8xOB2KE9rsHpC5u9VD@mail.gmail.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>	<4C2E395E.4010101@dcsoftware.com>	<001f01cb1a47$b50eb030$1f2c1090$@com>	<4C2E8AA7.4000109@dcsoftware.com>	<AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>	<4C2E9219.4090805@san-dc.com>	<AANLkTin-b0HlmdL9rdXNnALHko8UaYOllam2VU1Z22Tn@mail.gmail.com>
	<AANLkTinvamCgOWzvm1by38hpOU8xOB2KE9rsHpC5u9VD@mail.gmail.com>
Message-ID: <4C2E9610.6010307@san-dc.com>

On 07/02/2010 06:32 PM, David Hutto wrote:
> On Fri, Jul 2, 2010 at 9:31 PM, David Hutto<smokefloat at gmail.com>  wrote:
>    
>>
>> Well, it was mainly that he said he was a beginner and was only using
>> this for a single banking project, I do believe.
>>
>> Not that learning a new package would
> wouldn't
>
>
>   be helpful, I like
>    
>> experimenting, and failing/succeeding, but if this is all he needs to
>> accomplish, then not using more than is necessary would be beneficial.
>> A simple script, with simple sqlite fields to maintain.
>>
>>      

David:  Experimenting, failing and succeeding is the life of a 
programmer.  I have been programming for many years in assemply, 
FORTRAN, COBOL, Basic, RPG, FoxPro, C, but I am now totally committed to 
Python.  It is the best of all worlds.  Coming from the Microsoft side, 
open source and Python creates a whole new set of problems.  Do I use 
Windows?  Do I use Linux?  Do I use my Mac Book Pro?  You do have to 
make some decisions before moving on.  The choices are endless.

I have found Dabo and Django to be beneficial for me because they target 
what I want to do.

Your mileage may vary.  ;^)

-- 
Jeff

---------------

Jeff Johnson
jeff at san-dc.com
(623) 582-0323

www.san-dc.com


From jeff at san-dc.com  Sat Jul  3 03:55:02 2010
From: jeff at san-dc.com (Jeff Johnson)
Date: Fri, 02 Jul 2010 18:55:02 -0700
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <AANLkTimP74mVLRPV051nvW9KJ6OqXcGBYUkryXKmiewe@mail.gmail.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>	<4C2E395E.4010101@dcsoftware.com>	<001f01cb1a47$b50eb030$1f2c1090$@com>	<4C2E8AA7.4000109@dcsoftware.com>	<AANLkTilTytUQKe5StFKm6GxFN8P8WWL472NkqAdd1uY2@mail.gmail.com>	<4C2E9219.4090805@san-dc.com>	<AANLkTin-b0HlmdL9rdXNnALHko8UaYOllam2VU1Z22Tn@mail.gmail.com>	<AANLkTinvamCgOWzvm1by38hpOU8xOB2KE9rsHpC5u9VD@mail.gmail.com>	<4C2E9610.6010307@san-dc.com>
	<AANLkTimP74mVLRPV051nvW9KJ6OqXcGBYUkryXKmiewe@mail.gmail.com>
Message-ID: <4C2E9876.5030307@san-dc.com>

On 07/02/2010 06:51 PM, David Hutto wrote:
> In the end, there might be so many packages, I might not be able to
> handle it all(for my own uses). But, I would think, you would agree
> that a simple account balance app, would be no more than tkinter with
> a few functions to write and retrieve data from a sqlite db. To quote
> Sherlock, 'Sometimes, after eliminating the impossible, what ever is
> left, no matter how improbable, must be the solution.', or something
> like that.
>    

David:  I like your quote!  I am a huge Sherlock Holmes fan.  I like 
Dabo because I develop commercial applications.

-- 
Jeff

---------------

Jeff Johnson
jeff at san-dc.com
(623) 582-0323

www.san-dc.com


From jeff at san-dc.com  Sat Jul  3 06:44:47 2010
From: jeff at san-dc.com (Jeff Johnson)
Date: Fri, 02 Jul 2010 21:44:47 -0700
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <4C2EAC3C.2000507@gmail.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>	<4C2E395E.4010101@dcsoftware.com>	<001f01cb1a47$b50eb030$1f2c1090$@com>	<4C2E8AA7.4000109@dcsoftware.com>
	<4C2EAC3C.2000507@gmail.com>
Message-ID: <4C2EC03F.2070802@san-dc.com>

On 07/02/2010 08:19 PM, bob gailer wrote:
> On 7/2/2010 5:56 PM, Jeff Johnson wrote:
>> [snip]
>
>> Visual FoxPro ... is very similar to Access
>>
> I differ. Access and FoxPro are very different. Yes they both use 
> tables, relationships, indexes and SQL. Yes they both have visual 
> designers for forms and reports. Yes they both are programmable.
>
> But the differences are much more dramatic than the commonalities. I 
> have developed in both. I find it painful to work in one while 
> desiring a feature that exists only in the other.
>
> -- 
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
>    
Dare you say which?   ;^)


-- 
Jeff

---------------

Jeff Johnson
jeff at san-dc.com
(623) 582-0323

www.san-dc.com

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100702/7aa26733/attachment.html>

From schoappied at gmail.com  Sat Jul  3 14:03:49 2010
From: schoappied at gmail.com (Schoap D)
Date: Sat, 3 Jul 2010 14:03:49 +0200
Subject: [Tutor] help learning python
Message-ID: <AANLkTilJWH4obaGdVQI-DGrQEgRqdErlh5RoCo3LDW6V@mail.gmail.com>

Hi,

I'm busy with this tutorial
http://www.openbookproject.net/thinkCSpy/index.html
I need some feedback and help to be able to learn Python.

For instance, now I'm working on chapter 8, 8.13 exercise 1, 2 and 3. Code
become pretty complex for me there:
http://www.openbookproject.net/thinkCSpy/ch08.html

Exercise 1, I tried to solve with:

mitt = Box((780, 300), mitt_x, mitt_y, filled=True, thickness=1)

I added 780 and 300 as center for the paddle, is that right?

Exercise 2: I have this code now:
http://paste.pocoo.org/show/233057/

What do you think of the code? Is it right? Also within the context of the
pong code?

Next step will be to let the ball bounce back and to replace the distance
function with the new hit fuction in the pong code. But I'm not sure how and
where to place the call to the hit function in pong code... Please give some
feedback and help.

Thanks in advance,

Dirk
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100703/04445e72/attachment.html>

From johnf at jfcomputer.com  Sat Jul  3 15:34:29 2010
From: johnf at jfcomputer.com (John)
Date: Sat, 3 Jul 2010 06:34:29 -0700
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <4C2EAC3C.2000507@gmail.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
	<4C2E8AA7.4000109@dcsoftware.com> <4C2EAC3C.2000507@gmail.com>
Message-ID: <201007030634.29191.johnf@jfcomputer.com>

On Friday 02 July 2010 08:19:24 pm bob gailer wrote:
> On 7/2/2010 5:56 PM, Jeff Johnson wrote:
> > [snip]
> >
> > Visual FoxPro ... is very similar to Access
>
> I differ. Access and FoxPro are very different. Yes they both use
> tables, relationships, indexes and SQL. Yes they both have visual
> designers for forms and reports. Yes they both are programmable.
>
> But the differences are much more dramatic than the commonalities. I
> have developed in both. I find it painful to work in one while desiring
> a feature that exists only in the other.

Yes I agree (0ver 20 years with Fox/dBase) they are different.  I'd say Access 
provides several no thinking tools for the end user where VFP requires a 
little more effort.  But the concepts of both are very close.   The 
underlying code is also very different in that I find VFP 10 times easier 
when working with data.

That said, the question at hand is does Dabo make a good fit for the poster.  
I'd say without question the answer is yes.  Yes it is true that Dabo follows 
VFP more closely than Access.  But if the poster is moving from Access to a 
python solution does it matter?  The poster is making a change to a new 
language which is a major change.  At least Dabo keeps many of the concepts a 
Access user already understands. Therefore he/she will be more productive.

Johnf

From jf_byrnes at comcast.net  Sat Jul  3 17:25:20 2010
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Sat, 03 Jul 2010 10:25:20 -0500
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <4C2E604C.6030608@dcsoftware.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
	<4C2E604C.6030608@dcsoftware.com>
Message-ID: <4C2F5660.60201@comcast.net>

Jeff Johnson wrote:
> On 07/02/2010 11:40 AM, Chris C. wrote: I'm writing this question
> because I want, for my own satisfaction, to rewrite one of my Access dbs
> (one that does our finances) into a stand-alone Python database program
> using SQLite. I know I'll be learning as I go, but that'll work, I'm not
> in a big hurry and I'll work on it in my spare time. Right now I'm
> trying to get organized and get a game plan, and that's where I need help.
>
> I have been developing database applications for 20 years using FoxPro
> and VFP. Now I am developing using Dabo. Dabo is a framework wrapper for
> wxPython written totally in Python. I use SQLite for small applications
> and PostgreSQL for larger ones. Dabo was written by two of the top
> FoxPro developers and is supported by many others all over the world.
>
> http://dabodev.com/
>
> Please check it out. And go to www.leafe.com and subscribe to the
> dabo-user email list.
>

I would like to try out Dabo, but I don't see it in the Ubuntu 
repositories and I would like to avoid using svn if I can.  I didn't 
subscribe to the mailing list but I did read the archives and saw a 
thread about making a deb package.  It seems to have ended in April 
without a clear resolution.

So is there a package available so I can use the Ubuntu package manager 
to install it?

Thanks,  Jim


From bgailer at gmail.com  Sun Jul  4 04:53:07 2010
From: bgailer at gmail.com (bob gailer)
Date: Sat, 03 Jul 2010 19:53:07 -0700
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <4C2EC03F.2070802@san-dc.com>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>	<4C2E395E.4010101@dcsoftware.com>	<001f01cb1a47$b50eb030$1f2c1090$@com>	<4C2E8AA7.4000109@dcsoftware.com>	<4C2EAC3C.2000507@gmail.com>
	<4C2EC03F.2070802@san-dc.com>
Message-ID: <4C2FF793.1030508@gmail.com>

On 7/2/2010 9:44 PM, Jeff Johnson wrote:
> On 07/02/2010 08:19 PM, bob gailer wrote:
>> On 7/2/2010 5:56 PM, Jeff Johnson wrote:
>>> [snip]
>>
>>> Visual FoxPro ... is very similar to Access
>>>
>> I differ. Access and FoxPro are very different. Yes they both use 
>> tables, relationships, indexes and SQL. Yes they both have visual 
>> designers for forms and reports. Yes they both are programmable.
>>
>> But the differences are much more dramatic than the commonalities. I 
>> have developed in both. I find it painful to work in one while 
>> desiring a feature that exists only in the other.
>>
> Dare you say which?   ;^)

FoxPro
- more complete and easy-to-use object orientation
   - classes don't need to be in separate modules
   - classes and controls can be subclassed
   - controls can be encapsulated in container classes
   - classes have constructor methods - so possible to pass parameters
- forms do not contain any "magic" events
- method editor is a simple text editor
   - no "magic" events
   - no separate application window for programming
- each table, database container, program, index is a separate file
- there is a command window and lots of interactively useful commands
   - I like being able to run SQL and data manipulation statements directly.
- error handling is much better
- there are no misleading or confusing error messages that result from 
compilation problems
- SQL is integrated into the language
- nice set of workarea commands (scan, replace, ....)
- writing programs in FoxPro much easier than in VBA
- no need to separate application from data (that is automatic).
- no confusion about when to use . vs !

Access:
- query and report designers are much much better
   - the VFP report designer is incredibly limited and hard to work with 
by comparison.
- debugger does not require separate window
- subforms
- recordset controls on forms
- table designer has more features
- there is no database container or need for one.
- relationships are integrated - visually created and available in query 
designer.

That is not an exhaustive list - and it is my opinion. I'd rather not 
get into any religious arguments - but I'd be glad to clarify.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100703/ae3c1e09/attachment-0001.html>

From mwalsh at mwalsh.org  Sun Jul  4 07:06:32 2010
From: mwalsh at mwalsh.org (Martin Walsh)
Date: Sun, 04 Jul 2010 00:06:32 -0500
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <4C2F5660.60201@comcast.net>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>	<4C2E604C.6030608@dcsoftware.com>
	<4C2F5660.60201@comcast.net>
Message-ID: <4C3016D8.70509@mwalsh.org>

On 07/03/2010 10:25 AM, Jim Byrnes wrote:
> Jeff Johnson wrote:

[snip]

>> http://dabodev.com/
>>
>> Please check it out. And go to www.leafe.com and subscribe to the
>> dabo-user email list.
> 
> I would like to try out Dabo, but I don't see it in the Ubuntu
> repositories and I would like to avoid using svn if I can.  I didn't
> subscribe to the mailing list but I did read the archives and saw a
> thread about making a deb package.  It seems to have ended in April
> without a clear resolution.
> 
> So is there a package available so I can use the Ubuntu package manager
> to install it?

Unfortunately, after poking around a bit it would seem the only reliable
way of installing dabo for Linux at the moment is checking out trunk
from the project's subversion repository. Someone better informed should
feel free to set the record straight, if I am mistaken.

If your interest in a deb package is mainly the ability to uninstall,
then I'd recommend using virtualenv[1] until a suitable deb package is
released. The steps would be roughly this (untested) ...

$ sudo apt-get install python-reportlab python-wxgtk2.8
$ sudo apt-get install subversion python-virtualenv
$ virtualenv daboenv
$ cd daboenv
$ source bin/activate # this is important
# now we install dabo as recommended, adapted from:
#   http://wiki.dabodev.com/InstallationOnLinux
(daboenv)$
(daboenv)$ mkdir src && cd src
(daboenv)$ svn co http://svn.dabodev.com/dabo/trunk dabo
(daboenv)$ cd dabo
(daboenv)$ python setup.py install # no sudo!
# and run the demo to verify the installation
(daboenv)$ demo/DaboDemo.py

...

Hmm, this might seem like a lot of work -- but by using this method,
dabo is installed under daboenv and not in the system-wide site-packages
-- particularly useful for evaluation, IMO. YMMV.

HTH,
Marty

[1] http://virtualenv.openplans.org/

From jeff at san-dc.com  Sun Jul  4 05:17:01 2010
From: jeff at san-dc.com (Jeff Johnson)
Date: Sat, 03 Jul 2010 20:17:01 -0700
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <4C2F5660.60201@comcast.net>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>
	<4C2E604C.6030608@dcsoftware.com> <4C2F5660.60201@comcast.net>
Message-ID: <4C2FFD2D.2080209@san-dc.com>

On 07/03/2010 08:25 AM, Jim Byrnes wrote:
> Jeff Johnson wrote:
>> On 07/02/2010 11:40 AM, Chris C. wrote: I'm writing this question
>> because I want, for my own satisfaction, to rewrite one of my Access dbs
>> (one that does our finances) into a stand-alone Python database program
>> using SQLite. I know I'll be learning as I go, but that'll work, I'm not
>> in a big hurry and I'll work on it in my spare time. Right now I'm
>> trying to get organized and get a game plan, and that's where I need 
>> help.
>>
>> I have been developing database applications for 20 years using FoxPro
>> and VFP. Now I am developing using Dabo. Dabo is a framework wrapper for
>> wxPython written totally in Python. I use SQLite for small applications
>> and PostgreSQL for larger ones. Dabo was written by two of the top
>> FoxPro developers and is supported by many others all over the world.
>>
>> http://dabodev.com/
>>
>> Please check it out. And go to www.leafe.com and subscribe to the
>> dabo-user email list.
>>
>
> I would like to try out Dabo, but I don't see it in the Ubuntu 
> repositories and I would like to avoid using svn if I can.  I didn't 
> subscribe to the mailing list but I did read the archives and saw a 
> thread about making a deb package.  It seems to have ended in April 
> without a clear resolution.
>
> So is there a package available so I can use the Ubuntu package 
> manager to install it?
>
> Thanks,  Jim
>
I use Ubuntu 10.04 and Windows XP.  The developers of Dabo use Mac and 
Ubuntu.  Dabo runs without modification on all three major platforms.  
It is a given that while Ubuntu is awesome at supplying packages, there 
might be some that you have to go get.

That's all I can say about that.

-- 
Jeff

---------------

Jeff Johnson
jeff at san-dc.com
(623) 582-0323

www.san-dc.com


From speederpython at gmail.com  Sun Jul  4 15:20:48 2010
From: speederpython at gmail.com (John Palmer)
Date: Sun, 4 Jul 2010 14:20:48 +0100
Subject: [Tutor] Help with exercises from learning to program python
	wikibooks
Message-ID: <AANLkTilOtgvXNfzf7kbb_BmExy9FOH3NcYd96W6rHLic@mail.gmail.com>

Hi

I've just decided to try an learn python but i'm already stuck on one of the
first exercises, i've given the link below:

http://en.wikibooks.org/wiki/Python_Programming/Creating_Python_programs

The exercise that i'm stuck on is number three:

I've looked at the solution but it appears not to be working when i use this
code

print ("Hello, ", end=" " )
print ("world!")


I get the following error:

File "hello.py", line 1
    print ("Hello, ", end=" " )
                         ^
SyntaxError: invalid syntax



I've tried every changing where the white space is and the commas but i just
cant get it to work.

any help would be much appreciated and thank you in advance

John
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100704/ba60d1fa/attachment.html>

From hugo.yoshi at gmail.com  Sun Jul  4 15:32:23 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sun, 4 Jul 2010 15:32:23 +0200
Subject: [Tutor] Help with exercises from learning to program python
	wikibooks
In-Reply-To: <AANLkTilOtgvXNfzf7kbb_BmExy9FOH3NcYd96W6rHLic@mail.gmail.com>
References: <AANLkTilOtgvXNfzf7kbb_BmExy9FOH3NcYd96W6rHLic@mail.gmail.com>
Message-ID: <AANLkTinYhcZE6UJE5m3iWVIb4fLZgGisY16DDtgqMYQS@mail.gmail.com>

On Sun, Jul 4, 2010 at 3:20 PM, John Palmer <speederpython at gmail.com> wrote:
> Hi
>
> I've just decided to try an learn python but i'm already stuck on one of the
> first exercises, i've given the link below:
>
> http://en.wikibooks.org/wiki/Python_Programming/Creating_Python_programs
>
> The exercise that i'm stuck on is number three:
>
> I've looked at the solution but it appears not to be working when i use this
> code
>
> print ("Hello, ", end=" " )
>
> print ("world!")
>
> I get the following error:
>
> File "hello.py", line 1
> ??? print ("Hello, ", end=" " )
> ???????????????????????? ^
> SyntaxError: invalid syntax
>
>
>
> I've tried every changing where the white space is and the commas but i just
> cant get it to work.
>

Check your python version (type "python --version" on the command
line). This tutorial was made for versions 3.0 and later, and the
error suggest you have an older version than that. Some rather big
changes happened around the 3.0 release.

It should work if you replace the program with this:

print "hello", "world!"

But I recommend you get a tutorial that matches your python version
(or vice versa). Things will be very confusing if you don't

Hugo

From alan.gauld at btinternet.com  Sun Jul  4 16:14:09 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 4 Jul 2010 15:14:09 +0100
Subject: [Tutor] Help with exercises from learning to program
	pythonwikibooks
References: <AANLkTilOtgvXNfzf7kbb_BmExy9FOH3NcYd96W6rHLic@mail.gmail.com>
Message-ID: <i0q4vi$u2r$1@dough.gmane.org>


"John Palmer" <speederpython at gmail.com> wrote

> I've looked at the solution but it appears not to be working when i 
> use this
> code

> File "hello.py", line 1
>    print ("Hello, ", end=" " )
>                         ^
> SyntaxError: invalid syntax

This is Python V3 syntax, I suspect you have Python v2 installed.
This is not necessarily a bad thing since Python v3 is very new
and many applicationsd still require v2. But if you are learning
then you need to match your tutorial to the python version or vice
versa. So either find a Python v2 tutorial or upgrade Python to v3.1.
Until recently I'd have said go with v2 but I think v3 is becoming
sufficiently mature that I'd now suggest upgrading. By the time
you are fluent the external libraries etc should have mostly
caught up.

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



From zubin.mithra at gmail.com  Sun Jul  4 16:39:13 2010
From: zubin.mithra at gmail.com (Zubin Mithra)
Date: Sun, 4 Jul 2010 20:09:13 +0530
Subject: [Tutor] Help with exercises from learning to program python
	wikibooks
In-Reply-To: <AANLkTinYhcZE6UJE5m3iWVIb4fLZgGisY16DDtgqMYQS@mail.gmail.com>
References: <AANLkTilOtgvXNfzf7kbb_BmExy9FOH3NcYd96W6rHLic@mail.gmail.com>
	<AANLkTinYhcZE6UJE5m3iWVIb4fLZgGisY16DDtgqMYQS@mail.gmail.com>
Message-ID: <AANLkTilYfGuGi1qKFns6jvFt9339cHPwCXXEtpnZXNFP@mail.gmail.com>

On Sun, Jul 4, 2010 at 7:02 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote:

> On Sun, Jul 4, 2010 at 3:20 PM, John Palmer <speederpython at gmail.com>
> wrote:
> > Hi
> >
> > I've just decided to try an learn python but i'm already stuck on one of
> the
> > first exercises, i've given the link below:
> >
> > http://en.wikibooks.org/wiki/Python_Programming/Creating_Python_programs
> >
> > The exercise that i'm stuck on is number three:
>

The Python tutorial for both 2.x and 3.0 is really good.
Python 2.x - http://docs.python.org/tutorial/
Python 3.0 - http://docs.python.org/release/3.0.1/tutorial/

Have fun learning Python!

zsm
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100704/27bedfc2/attachment.html>

From hugo.yoshi at gmail.com  Sun Jul  4 16:42:44 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sun, 4 Jul 2010 16:42:44 +0200
Subject: [Tutor] Help with exercises from learning to program python
	wikibooks
In-Reply-To: <AANLkTikBn26g0f_MJBvOxLVTd6mi35wLTAy_SHBAgsJw@mail.gmail.com>
References: <AANLkTilOtgvXNfzf7kbb_BmExy9FOH3NcYd96W6rHLic@mail.gmail.com> 
	<AANLkTinYhcZE6UJE5m3iWVIb4fLZgGisY16DDtgqMYQS@mail.gmail.com> 
	<AANLkTikBn26g0f_MJBvOxLVTd6mi35wLTAy_SHBAgsJw@mail.gmail.com>
Message-ID: <AANLkTim7653KYpg57dX0na5twpK1tvZT7fViOsKA4KXV@mail.gmail.com>

CC'd to tutor for completeness

On Sun, Jul 4, 2010 at 3:58 PM, John Palmer <speederpython at gmail.com> wrote:
> yep i'm using version 2.6.5.
>
> Would you recommend using the newer version? as on the python website it
> seems to imply that the different versions have different uses and if in
> doubt you should use version 2?
>
> Thanks a lot for the help it is much appreciated
>
> John
>

Well, some people say you're better off learning version 2 for now,
since a lot of code out there is still for that version. The
differences aren't really that earth-shocking though, especially once
you get fluent in the language.

I'd say go with 3.x and learn that. You shouldn't have a big problem
reading 2.x code, and writing it will become easier the more you
learn. And 3.x really is the future of python

Hugo

From srih4ri at gmail.com  Sun Jul  4 20:17:12 2010
From: srih4ri at gmail.com (Srihari k)
Date: Sun, 4 Jul 2010 23:47:12 +0530
Subject: [Tutor] Running a python script as root.
Message-ID: <AANLkTilQ6EUdz7o5b7dIrcNM7YiSvaAROSw5MIVEdXe8@mail.gmail.com>

I have a small script that uses python-gammu to read time from my
phone and set the system time:

#!/usr/bin/python
import gammu
sm=gammu.StateMachine()
sm.ReadConfig()
sm.Init()
cell_time=sm.GetDateTime()
import os
os.system('date -s \'%s\''% cell_time)

Now this script works when i run it as root(#)./settime.py or do a
$sudo ./settime.py
When i run it as normal user $./settime.py (as expected) the following
error occurs:

date: cannot set date: Operation not permitted
Sun Jul  4 23:37:37 IST 2010

This is because the normal user is not allowed to set the time using
date -s command.

I did #chmod +s settime.py so that SUID bit be set and all users can
execute the script and set the system time.
now the permissions of file are:
-rwsr-xr-x 1 root root 165 2010-07-04 23:16 settime.py


The script still works as before ..
date: cannot set date: Operation not permitted
Sun Jul  4 23:37:37 IST 2010

I guess this because the python interpreter is still being run by the
normal user and is unprivileged to set the date ? Is it ?



Now how do i make this script work for everyone?

Thanks in advance,
-- 
Srihari K

From alan.gauld at btinternet.com  Sun Jul  4 21:29:54 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 4 Jul 2010 20:29:54 +0100
Subject: [Tutor] Running a python script as root.
References: <AANLkTilQ6EUdz7o5b7dIrcNM7YiSvaAROSw5MIVEdXe8@mail.gmail.com>
Message-ID: <i0qnfi$j07$1@dough.gmane.org>

"Srihari k" <srih4ri at gmail.com> wrote
> The script still works as before ..
> date: cannot set date: Operation not permitted
> Sun Jul  4 23:37:37 IST 2010
>
> I guess this because the python interpreter is still being run by 
> the
> normal user and is unprivileged to set the date ? Is it ?

I'd hope so! No matter what the script it should still be subject to
the restrictions of the user - otherwise guest users etc could
potentially create havoc.

Setting the time is a serious operation on a shared system
or server since it could cause some time based apps to miss
a vital run sequence, or upset build operations in a development
environment. You may only use your PC as a single user
environment but *nix doesn't know that!

sudo is there for a reason, learn to love it, as it protects you
from yourself

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



From rdmoores at gmail.com  Mon Jul  5 00:32:51 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sun, 4 Jul 2010 15:32:51 -0700
Subject: [Tutor] Help with exercises from learning to program python
	wikibooks
In-Reply-To: <AANLkTilYfGuGi1qKFns6jvFt9339cHPwCXXEtpnZXNFP@mail.gmail.com>
References: <AANLkTilOtgvXNfzf7kbb_BmExy9FOH3NcYd96W6rHLic@mail.gmail.com> 
	<AANLkTinYhcZE6UJE5m3iWVIb4fLZgGisY16DDtgqMYQS@mail.gmail.com> 
	<AANLkTilYfGuGi1qKFns6jvFt9339cHPwCXXEtpnZXNFP@mail.gmail.com>
Message-ID: <AANLkTim5aPOXzOJDOar6C-Z172iXrgp2R1JR0rAUcLzh@mail.gmail.com>

On Sun, Jul 4, 2010 at 07:39, Zubin Mithra <zubin.mithra at gmail.com> wrote:

> The Python tutorial for both 2.x and 3.0 is really good.
> Python 2.x - http://docs.python.org/tutorial/
> Python 3.0 - http://docs.python.org/release/3.0.1/tutorial/

The 3.0 link is broken. Try <http://docs.python.org/py3k/tutorial/>

Dick Moores

From jf_byrnes at comcast.net  Mon Jul  5 03:30:37 2010
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Sun, 04 Jul 2010 20:30:37 -0500
Subject: [Tutor] Help with choices for new database program
In-Reply-To: <4C3016D8.70509@mwalsh.org>
References: <001501cb1a16$1a1a8760$4e4f9620$@com>	<4C2E604C.6030608@dcsoftware.com>	<4C2F5660.60201@comcast.net>
	<4C3016D8.70509@mwalsh.org>
Message-ID: <4C3135BD.60300@comcast.net>

Martin Walsh wrote:
> On 07/03/2010 10:25 AM, Jim Byrnes wrote:
>> Jeff Johnson wrote:
>
> [snip]
>
>>> http://dabodev.com/
>>>
>>> Please check it out. And go to www.leafe.com and subscribe to the
>>> dabo-user email list.
>>
>> I would like to try out Dabo, but I don't see it in the Ubuntu
>> repositories and I would like to avoid using svn if I can.  I didn't
>> subscribe to the mailing list but I did read the archives and saw a
>> thread about making a deb package.  It seems to have ended in April
>> without a clear resolution.
>>
>> So is there a package available so I can use the Ubuntu package manager
>> to install it?
>
> Unfortunately, after poking around a bit it would seem the only reliable
> way of installing dabo for Linux at the moment is checking out trunk
> from the project's subversion repository. Someone better informed should
> feel free to set the record straight, if I am mistaken.
>
> If your interest in a deb package is mainly the ability to uninstall,
> then I'd recommend using virtualenv[1] until a suitable deb package is
> released. The steps would be roughly this (untested) ...

That's part of it but mainly it's that they are so easy to install.

> $ sudo apt-get install python-reportlab python-wxgtk2.8
> $ sudo apt-get install subversion python-virtualenv
> $ virtualenv daboenv
> $ cd daboenv
> $ source bin/activate # this is important
> # now we install dabo as recommended, adapted from:
> #   http://wiki.dabodev.com/InstallationOnLinux
> (daboenv)$
> (daboenv)$ mkdir src&&  cd src
> (daboenv)$ svn co http://svn.dabodev.com/dabo/trunk dabo
> (daboenv)$ cd dabo
> (daboenv)$ python setup.py install # no sudo!
> # and run the demo to verify the installation
> (daboenv)$ demo/DaboDemo.py
>
> ...
>
> Hmm, this might seem like a lot of work -- but by using this method,
> dabo is installed under daboenv and not in the system-wide site-packages
> -- particularly useful for evaluation, IMO. YMMV.

I read the website [1] and being new to linux there was a lot I did not 
understand.  I think I will go the svn route on a test machine before I 
put it on my main machine.

> HTH,
> Marty
>
> [1] http://virtualenv.openplans.org/

Thanks, Jim


From rdmoores at gmail.com  Mon Jul  5 09:27:08 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Mon, 5 Jul 2010 00:27:08 -0700
Subject: [Tutor] "x and y" means "if x is false, then x, else y"??
Message-ID: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com>

See <http://docs.python.org/py3k/library/stdtypes.html#boolean-operations-and-or-not>.
I am quite familiar with the meaning of "x and y" in Python, and how
it is evaluated -- first x, and only if x is False, then evaluate y.
But I just can't read "if x is false, then x, else y" that way. In
fact, I can't read it at all. Is this a mistake in the Python 3 docs?
If not, can someone tell me how to make sense of it?

BTW I came across this while reading the ingenuously designed and
remarkably clear Chapter 2 of Mark Pilgrim's "Dive Into Python".
(<http://diveintopython3.org/>). A link down at the bottom of
<http://diveintopython3.org/native-datatypes.html>, in Section 2.9
"Further Reading, Boolean Operations", took me to that section of the
docs.

Thanks,

Dick Moores

From steve at alchemy.com  Mon Jul  5 09:55:28 2010
From: steve at alchemy.com (Steve Willoughby)
Date: Mon, 05 Jul 2010 00:55:28 -0700
Subject: [Tutor] "x and y" means "if x is false, then x, else y"??
In-Reply-To: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com>
References: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com>
Message-ID: <4C318FF0.8020602@alchemy.com>

On 05-Jul-10 00:27, Richard D. Moores wrote:
> See<http://docs.python.org/py3k/library/stdtypes.html#boolean-operations-and-or-not>.
> I am quite familiar with the meaning of "x and y" in Python, and how
> it is evaluated -- first x, and only if x is False, then evaluate y.
> But I just can't read "if x is false, then x, else y" that way. In
> fact, I can't read it at all. Is this a mistake in the Python 3 docs?
> If not, can someone tell me how to make sense of it?

Yes, in fact this was a common idiom before Python picked up the (x if p 
else y) syntax, and something of this nature is still commonplace in the 
Perl world (even though it has the ?: operator anyway).

You already know about the "short circuiting" effect of "and" and "or", 
which affects whether the right argument is even evaluated at all, but 
the other piece of this puzzle is that the _return value_ of the 
expression is not a pure Boolean value of True or False, but is in fact 
either the value x or y itself.

So in the case of
     x and y
if x is true, then we need to evaluate y, in which case y is returned. 
If y happened to be true, then that means both x and y were true, and 
hence the entire expression is true.  The particular "true" value we 
return here happens to be the (true) value of y.

If y is false, then returning it yields the correct false value for the 
whole expression, although the actual (false) value of y is what we return.

If x if false, then we need go no further and simply return x.

So.


1 and 2  ==>  2    (true and true ==> true)
0 and 5  ==>  0    (false and true ==> false)
'hello' and '' ==> '' (true and false ==> false)
'xx' and 'yy' ==> 'yy' (true and true ==> true)

x and y  ==>  x if x is false, else y


Some people like using this to set values to defaults if no (true) value 
was input, in a semantically pleasing manner, thus:

def __init__(self, a=None, b=None):
   self.a = a or 123
   self.b = b or 456



From rdmoores at gmail.com  Mon Jul  5 11:37:12 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Mon, 5 Jul 2010 02:37:12 -0700
Subject: [Tutor] "x and y" means "if x is false, then x, else y"??
In-Reply-To: <4C318FF0.8020602@alchemy.com>
References: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com> 
	<4C318FF0.8020602@alchemy.com>
Message-ID: <AANLkTimxON5RbEPCSkHnrPvwItqwtV0YNegZxFGrqNvY@mail.gmail.com>

On Mon, Jul 5, 2010 at 00:55, Steve Willoughby <steve at alchemy.com> wrote:
> On 05-Jul-10 00:27, Richard D. Moores wrote:
>>
>>
>> See<http://docs.python.org/py3k/library/stdtypes.html#boolean-operations-and-or-not>.
>> I am quite familiar with the meaning of "x and y" in Python, and how
>> it is evaluated -- first x, and only if x is False, then evaluate y.
>> But I just can't read "if x is false, then x, else y" that way. In
>> fact, I can't read it at all. Is this a mistake in the Python 3 docs?
>> If not, can someone tell me how to make sense of it?

> Yes, in fact this was a common idiom before Python picked up the (x if p
> else y) syntax, and something of this nature is still commonplace in the
> Perl world (even though it has the ?: operator anyway).
>
> You already know about the "short circuiting" effect of "and" and "or",
> which affects whether the right argument is even evaluated at all, but the
> other piece of this puzzle is that the _return value_ of the expression is
> not a pure Boolean value of True or False, but is in fact either the value x
> or y itself.
>
> So in the case of
>    x and y
> if x is true, then we need to evaluate y, in which case y is returned. If y
> happened to be true, then that means both x and y were true, and hence the
> entire expression is true.  The particular "true" value we return here
> happens to be the (true) value of y.
>
> If y is false, then returning it yields the correct false value for the
> whole expression, although the actual (false) value of y is what we return.
>
> If x if false, then we need go no further and simply return x.
>
> So.
>
>
> 1 and 2  ==>  2    (true and true ==> true)
> 0 and 5  ==>  0    (false and true ==> false)
> 'hello' and '' ==> '' (true and false ==> false)
> 'xx' and 'yy' ==> 'yy' (true and true ==> true)
>
> x and y  ==>  x if x is false, else y
>
>
> Some people like using this to set values to defaults if no (true) value was
> input, in a semantically pleasing manner, thus:
>
> def __init__(self, a=None, b=None):
>  self.a = a or 123
>  self.b = b or 456

Steve,

Your answer seems very well-formulated. However, I've read it over and
over, but I keep getting hung up over the meaning of "the return
value" of an expression. I am of course familiar with values returned
by a function, but don't quite grasp what the return value of, say,
the y of "x and y" might mean.
Also, you distinguish between a return value of True and and the value
of y being such (say 5, and not 0) that it makes y true (but not
True). So another  thing I need to know is the difference between True
and true.  Also between False and false. And why the difference is
important.

I'm thinking that possibly what would help would be to contextualize
"x and y" in some snippet of code. I'm sorry to trouble you with my
denseness.

Dick

From stefan_ml at behnel.de  Mon Jul  5 13:09:34 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Mon, 05 Jul 2010 13:09:34 +0200
Subject: [Tutor] "x and y" means "if x is false, then x, else y"??
In-Reply-To: <AANLkTimxON5RbEPCSkHnrPvwItqwtV0YNegZxFGrqNvY@mail.gmail.com>
References: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com>
	<4C318FF0.8020602@alchemy.com>
	<AANLkTimxON5RbEPCSkHnrPvwItqwtV0YNegZxFGrqNvY@mail.gmail.com>
Message-ID: <i0sehe$9j1$1@dough.gmane.org>

Richard D. Moores, 05.07.2010 11:37:
> I keep getting hung up over the meaning of "the return
> value" of an expression. I am of course familiar with values returned
> by a function, but don't quite grasp what the return value of, say,
> the y of "x and y" might mean.

Think of a different expression, like "1+1". Here, the return value (or 
maybe a better wording would be the result value) is 2.


> Also, you distinguish between a return value of True and and the value
> of y being such (say 5, and not 0) that it makes y true (but not
> True). So another  thing I need to know is the difference between True
> and true.  Also between False and false. And why the difference is
> important.

"True" is the value "True" in Python, which is a singleton. You can test 
for it by using

     x is True

However, other values can have a true values as well, without being True, e.g.

     if 1: print("TRUE!!!")

will actuall print the string, as the value 1 is considered true when 
turned into a boolean result.

Stefan


From rdmoores at gmail.com  Mon Jul  5 13:53:58 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Mon, 5 Jul 2010 04:53:58 -0700
Subject: [Tutor] "x and y" means "if x is false, then x, else y"??
In-Reply-To: <i0sehe$9j1$1@dough.gmane.org>
References: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com> 
	<4C318FF0.8020602@alchemy.com>
	<AANLkTimxON5RbEPCSkHnrPvwItqwtV0YNegZxFGrqNvY@mail.gmail.com> 
	<i0sehe$9j1$1@dough.gmane.org>
Message-ID: <AANLkTilh7dSrItv-pxDASPV9DkpHSjWx_c0Dwr0MPHQl@mail.gmail.com>

On Mon, Jul 5, 2010 at 04:09, Stefan Behnel <stefan_ml at behnel.de> wrote:
> Richard D. Moores, 05.07.2010 11:37:
>>
>> I keep getting hung up over the meaning of "the return
>> value" of an expression. I am of course familiar with values returned
>> by a function, but don't quite grasp what the return value of, say,
>> the y of "x and y" might mean.
>
> Think of a different expression, like "1+1". Here, the return value (or
> maybe a better wording would be the result value) is 2.
>
>
>> Also, you distinguish between a return value of True and and the value
>> of y being such (say 5, and not 0) that it makes y true (but not
>> True). So another ?thing I need to know is the difference between True
>> and true. ?Also between False and false. And why the difference is
>> important.
>
> "True" is the value "True" in Python, which is a singleton. You can test for
> it by using
>
> ? ?x is True

Ah. But could you give me an x that would satisfy that? I can think of

>>> (5 > 4) is True
True

But how can (5 > 4) be an x? Could you show me some code where it could be?

>>> x = (5 > 4)
>>> x
True
>>> x is True
True

So it can! That surprised me.  I was expecting   "x = (5 > 4)"  to be
absurd -- raise an exception? Still seems pretty weird.

> However, other values can have a true values as well, without being True,
> e.g.
>
> ? ?if 1: print("TRUE!!!")
> will actually print the string, as the value 1 is considered true when turned
> into a boolean result.

Yes, I see that.

Well, maybe I'm getting there.

Thanks,

Dick
--------------
CAUTION: Pseudo Vorticity Advection

From wprins at gmail.com  Mon Jul  5 13:54:46 2010
From: wprins at gmail.com (Walter Prins)
Date: Mon, 5 Jul 2010 12:54:46 +0100
Subject: [Tutor] "x and y" means "if x is false, then x, else y"??
In-Reply-To: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com>
References: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com>
Message-ID: <AANLkTinZ5bJ0DRGZZRUU0bxvJHaCcrn7IEOcLDUFpEDj@mail.gmail.com>

On 5 July 2010 08:27, Richard D. Moores <rdmoores at gmail.com> wrote:

> See <
> http://docs.python.org/py3k/library/stdtypes.html#boolean-operations-and-or-not
> >.
> I am quite familiar with the meaning of "x and y" in Python, and how
> it is evaluated -- first x, and only if x is False, then evaluate y.
>

Sorry if this is being overly pedantic, but I thought I'd point out the
above isn't right as stated, although I understand what you're getting at
(re short circuit boolean evaluation) in general.  To be correct, I presume
you meant "OR" where you wrote "AND", as it would be correct in that case
e.g:

x AND y: Will only evaluate y if x is TRUE. (If x is FALSE then you don't
need to evaluate y since the resultant expression will be FALSE regardless,
see footnote 2 in the page you referenced.)

x OR y:  Will only evaluate y if x is FALSE. (If x is TRUE then you don't
need to evaluate y since the resultant expression will be TRUE regardless,
see footnote 1 in the page you referenced.)

See e.g. output of this. <http://pastebin.com/6c6UWcTQ>

So then, to explain this line from the page you reference: x and y:
"if *x*is false, then
*x*, else *y"

*Think about it: As per the above, if x is false, then because it's false,
Python need only and will only evaluate x, and will therefore essentially
return whatever "x" is when evaluating the expression.  If x is true on the
other hand, then by the above rules, it has to *also* evaluate y as well,
and so will end up effectively returning whatever y returns as it determines
what the truth value of the overall expression is.  Shortening that
reasoning, you can say, "if x is false, then x, else y". See?  (The same
sory of reasoning applies for the "or" case if you think it out.)
*
*Hope that helps.

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100705/0568a743/attachment.html>

From rdmoores at gmail.com  Mon Jul  5 14:17:05 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Mon, 5 Jul 2010 05:17:05 -0700
Subject: [Tutor] "x and y" means "if x is false, then x, else y"??
In-Reply-To: <AANLkTinZ5bJ0DRGZZRUU0bxvJHaCcrn7IEOcLDUFpEDj@mail.gmail.com>
References: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com> 
	<AANLkTinZ5bJ0DRGZZRUU0bxvJHaCcrn7IEOcLDUFpEDj@mail.gmail.com>
Message-ID: <AANLkTilmCNflz7T3ZeyD4_OxvqTP5EADk4TE-1uMhIYC@mail.gmail.com>

On Mon, Jul 5, 2010 at 04:54, Walter Prins <wprins at gmail.com> wrote:
>
>
> On 5 July 2010 08:27, Richard D. Moores <rdmoores at gmail.com> wrote:
>>
>> See
>> <http://docs.python.org/py3k/library/stdtypes.html#boolean-operations-and-or-not>.
>> I am quite familiar with the meaning of "x and y" in Python, and how
>> it is evaluated -- first x, and only if x is False, then evaluate y.
>
> Sorry if this is being overly pedantic, but I thought I'd point out the
> above isn't right as stated, although I understand what you're getting at
> (re short circuit boolean evaluation) in general.? To be correct, I presume
> you meant "OR" where you wrote "AND", as it would be correct in that case

Yes, my careless mistake. Instead of "first x, and only if x is False,
then evaluate y" I should have written "first x, and only if x is
True, then evaluate y", right?

> e.g:
>
> x AND y: Will only evaluate y if x is TRUE. (If x is FALSE then you don't
> need to evaluate y since the resultant expression will be FALSE regardless,
> see footnote 2 in the page you referenced.)
>
> x OR y:? Will only evaluate y if x is FALSE. (If x is TRUE then you don't
> need to evaluate y since the resultant expression will be TRUE regardless,
> see footnote 1 in the page you referenced.)
>
> See e.g. output of this.
>
> So then, to explain this line from the page you reference: x and y:? "if x
> is false, then x, else y"
>
> Think about it: As per the above, if x is false, then because it's false,
> Python need only and will only evaluate x, and will therefore essentially
> return whatever "x" is when evaluating the expression.? If x is true on the
> other hand, then by the above rules, it has to *also* evaluate y as well,
> and so will end up effectively returning whatever y returns as it determines
> what the truth value of the overall expression is.? Shortening that
> reasoning, you can say, "if x is false, then x, else y". See?? (The same
> sort of reasoning applies for the "or" case if you think it out.)
>
> Hope that helps.

Wow, it did! Especially that last big paragraph. Thanks, Walter!

Dick
---------------
CAUTION: Dynamic Inertial Balance

From adam.jtm30 at gmail.com  Mon Jul  5 14:21:21 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Mon, 5 Jul 2010 13:21:21 +0100
Subject: [Tutor] "x and y" means "if x is false, then x, else y"??
In-Reply-To: <AANLkTilh7dSrItv-pxDASPV9DkpHSjWx_c0Dwr0MPHQl@mail.gmail.com>
References: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com> 
	<4C318FF0.8020602@alchemy.com>
	<AANLkTimxON5RbEPCSkHnrPvwItqwtV0YNegZxFGrqNvY@mail.gmail.com> 
	<i0sehe$9j1$1@dough.gmane.org>
	<AANLkTilh7dSrItv-pxDASPV9DkpHSjWx_c0Dwr0MPHQl@mail.gmail.com>
Message-ID: <AANLkTimM8QQ9LxPhHwveFHt0LlxDLsGaeTrlkdFdw4m9@mail.gmail.com>

On 5 July 2010 12:53, Richard D. Moores <rdmoores at gmail.com> wrote:

> On Mon, Jul 5, 2010 at 04:09, Stefan Behnel <stefan_ml at behnel.de> wrote:
> > Richard D. Moores, 05.07.2010 11:37:
> >>
> >> I keep getting hung up over the meaning of "the return
> >> value" of an expression. I am of course familiar with values returned
> >> by a function, but don't quite grasp what the return value of, say,
> >> the y of "x and y" might mean.
> >
> > Think of a different expression, like "1+1". Here, the return value (or
> > maybe a better wording would be the result value) is 2.
> >
> >
> >> Also, you distinguish between a return value of True and and the value
> >> of y being such (say 5, and not 0) that it makes y true (but not
> >> True). So another  thing I need to know is the difference between True
> >> and true.  Also between False and false. And why the difference is
> >> important.
> >
> > "True" is the value "True" in Python, which is a singleton. You can test
> for
> > it by using
> >
> >    x is True
>
> Ah. But could you give me an x that would satisfy that? I can think of
>
> >>> (5 > 4) is True
> True
>
> But how can (5 > 4) be an x? Could you show me some code where it could be?
>
> >>> x = (5 > 4)
> >>> x
> True
> >>> x is True
> True
>
> So it can! That surprised me.  I was expecting   "x = (5 > 4)"  to be
> absurd -- raise an exception? Still seems pretty weird.
>

Greater than (>) works like the mathematical operators in returning a value,
it just happens that for comparison operators (>, <, ==, !=) the values can
only be True or False.

HTH,
Adam.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100705/cef0d801/attachment-0001.html>

From adam.jtm30 at gmail.com  Mon Jul  5 14:23:48 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Mon, 5 Jul 2010 13:23:48 +0100
Subject: [Tutor] "x and y" means "if x is false, then x, else y"??
In-Reply-To: <AANLkTimM8QQ9LxPhHwveFHt0LlxDLsGaeTrlkdFdw4m9@mail.gmail.com>
References: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com> 
	<4C318FF0.8020602@alchemy.com>
	<AANLkTimxON5RbEPCSkHnrPvwItqwtV0YNegZxFGrqNvY@mail.gmail.com> 
	<i0sehe$9j1$1@dough.gmane.org>
	<AANLkTilh7dSrItv-pxDASPV9DkpHSjWx_c0Dwr0MPHQl@mail.gmail.com> 
	<AANLkTimM8QQ9LxPhHwveFHt0LlxDLsGaeTrlkdFdw4m9@mail.gmail.com>
Message-ID: <AANLkTilaAD-8T27wCswUim3EtY4r30yP2HmjeyuZNxQl@mail.gmail.com>

On 5 July 2010 13:21, Adam Bark <adam.jtm30 at gmail.com> wrote:

> On 5 July 2010 12:53, Richard D. Moores <rdmoores at gmail.com> wrote:
>
>> On Mon, Jul 5, 2010 at 04:09, Stefan Behnel <stefan_ml at behnel.de> wrote:
>> > Richard D. Moores, 05.07.2010 11:37:
>> >>
>> >> I keep getting hung up over the meaning of "the return
>> >> value" of an expression. I am of course familiar with values returned
>> >> by a function, but don't quite grasp what the return value of, say,
>> >> the y of "x and y" might mean.
>> >
>> > Think of a different expression, like "1+1". Here, the return value (or
>> > maybe a better wording would be the result value) is 2.
>> >
>> >
>> >> Also, you distinguish between a return value of True and and the value
>> >> of y being such (say 5, and not 0) that it makes y true (but not
>> >> True). So another  thing I need to know is the difference between True
>> >> and true.  Also between False and false. And why the difference is
>> >> important.
>> >
>> > "True" is the value "True" in Python, which is a singleton. You can test
>> for
>> > it by using
>> >
>> >    x is True
>>
>> Ah. But could you give me an x that would satisfy that? I can think of
>>
>> >>> (5 > 4) is True
>> True
>>
>> But how can (5 > 4) be an x? Could you show me some code where it could
>> be?
>>
>> >>> x = (5 > 4)
>> >>> x
>> True
>> >>> x is True
>> True
>>
>> So it can! That surprised me.  I was expecting   "x = (5 > 4)"  to be
>> absurd -- raise an exception? Still seems pretty weird.
>>
>
> Greater than (>) works like the mathematical operators in returning a
> value, it just happens that for comparison operators (>, <, ==, !=) the
> values can only be True or False.
>
> HTH,
> Adam.
>

I should add that this is how something like:

if x != y:
    do_something()

works, if expects a True or False (this isn't always true but works for
comparison operators expressions such as this).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100705/efc1de6e/attachment.html>

From steve at pearwood.info  Mon Jul  5 15:18:47 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 5 Jul 2010 23:18:47 +1000
Subject: [Tutor] "x and y" means "if x is false, then x, else y"??
In-Reply-To: <AANLkTimxON5RbEPCSkHnrPvwItqwtV0YNegZxFGrqNvY@mail.gmail.com>
References: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com>
	<4C318FF0.8020602@alchemy.com>
	<AANLkTimxON5RbEPCSkHnrPvwItqwtV0YNegZxFGrqNvY@mail.gmail.com>
Message-ID: <201007052318.48054.steve@pearwood.info>

On Mon, 5 Jul 2010 07:37:12 pm Richard D. Moores wrote:
> On Mon, Jul 5, 2010 at 00:55, Steve Willoughby <steve at alchemy.com> 
wrote:
[...]
> Steve,
>
> Your answer seems very well-formulated. However, I've read it over
> and over, but I keep getting hung up over the meaning of "the return
> value" of an expression. I am of course familiar with values returned
> by a function, but don't quite grasp what the return value of, say,
> the y of "x and y" might mean.

At the risk of adding confusion by butting in (I'm also a Steve, just a 
different one...), perhaps a better expression would be just "the 
value" of an expression.

If you have any expression, such as:

23 + 42
"hello world".split()
len("abc")

then the expression has a value:

65
["hello", "world"]
3

That's what Steve means by "the return value".


> Also, you distinguish between a return value of True and and the
> value of y being such (say 5, and not 0) that it makes y true (but
> not True). So another  thing I need to know is the difference between
> True and true.  Also between False and false. And why the difference
> is important.

This is a fundamental part of Python's programming model: every object, 
without exception, can be used where some other languages insist on 
actual boolean flags. In Python, there's nothing special about True and 
False -- until version 2.3, they didn't even exist, and in fact they 
are implemented as a subclass of int. True is an alternative way of 
spelling 1, and False of 0:

>>> True*3
3
>>> False + 5
5

You can see more about the history of bool in Python here:
http://www.python.org/dev/peps/pep-0285/

Since Python allows direct boolean operations (if...else, and, or, not) 
on all objects, we need some rules for deciding what objects are 
considered True-like ("true") and which are considered False-like 
("false"). The distinction Python uses for built-ins is between 
something and nothing: an object which represents something is true, 
and one which represents nothing is false.

The most obvious example comes from numbers. Numbers which are equal to 
zero are obviously Nothing, and hence considered false. All other 
numbers are Something, and hence true.

Similarly for strings: the empty string is a string-flavoured Nothing, 
and all other strings are Something.

Collections -- lists, tuples and dicts -- are considered Nothing if they 
are empty, otherwise Something.

None is a special type of Nothing, and so is considered false.

When it comes to custom-built classes, rather than built-ins, the 
distinction may be a little weaker, since of course the programmer can 
define their class any way they like. Python first looks to see if the 
class has a __nonzero__ method, and if so, calls that. Otherwise it 
calls __len__. If the class has neither of those methods, it is 
automatically considered to be Something. So it's easy to create 
strange classes that don't quite fit into the Something/Nothing 
dichotomy:

class Funny:
    def __nonzero__(self):
        import time
        return time.time() % 2 == 0
        # true on even seconds, false on odd seconds

Python is quite happy to let you shoot yourself in the foot if you try.

Ruby has a similar policy, except in Ruby everything is true except for 
two objects: false and nil.

http://www.skorks.com/2009/09/true-false-and-nil-objects-in-ruby/

Other languages may make different choices.

In Python, True and False are merely the canonical true and false 
objects, and bool(x) will return the canonical Boolean value of x:

>>> bool(None)
False
>>> bool("something funny")
True

It is very rare you need to use bool. Don't write this:

if bool(x):
    ...

that's just a waste of a function call. It's *nearly* as silly as 
writing:

if (x==y) is True:  # Or should that be if (x==y) is True is True ?
    ...


> I'm thinking that possibly what would help would be to contextualize
> "x and y" in some snippet of code. I'm sorry to trouble you with my
> denseness.

s = some_string_value()
if not s:
    print "Empty string"
else:
    print "The string starts with", s[0]



people_with_red_hair = "Phil George Susan Samantha".split()
people_with_glasses = "Henry Felicity Michelle Mary-Anne Billy".split()
a = set(people_with_red_hair)
b = set(people_with_glasses)
if not a:
    print "There are no red-heads."
if not a.intersection(b):
    print "There are no red-heads who also wear glasses."




-- 
Steven D'Aprano

From delegbede at dudupay.com  Mon Jul  5 17:20:16 2010
From: delegbede at dudupay.com (Dipo Elegbede)
Date: Mon, 5 Jul 2010 16:20:16 +0100
Subject: [Tutor] raw_input
Message-ID: <AANLkTilwI4V7GkE1fCSrZ-0TiSLY6yaCsS2vjQbJI-f8@mail.gmail.com>

Hello,

I seem to be having problems with raw_input.

i wrote something like:

raw_input('Press Enter')

it comes back to tell me raw_input is not defined, a NameError!

Is it that something about it has changed in python 3.1 or I have been
writing the wrong thing.

Please enlighten me.

regards.

-- 
Elegbede Muhammed Oladipupo
OCA
+2348077682428
+2347042171716
www.dudupay.com
Mobile Banking Solutions | Transaction Processing | Enterprise Application
Development
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100705/c6cca2d2/attachment.html>

From prasadaraon50 at gmail.com  Mon Jul  5 17:31:32 2010
From: prasadaraon50 at gmail.com (prasad rao)
Date: Mon, 5 Jul 2010 21:01:32 +0530
Subject: [Tutor] endless loop
Message-ID: <AANLkTimhK_-NiOoSS48RCbKTSRouxDcka7MKrIhgKPJx@mail.gmail.com>

hi
  I am trying problem 6 in projecteuler.org.
What is the smallest positive number that is evenly divisible by all
of the numbers from 1 to 20?


def rr(z,m=1):
          q=lambda n:m%n==0
          s=lambda False : 0
          a=filter(s,map(q,range(1,z)))
          if not a:
              m+=1
              rr(z,m)
          else:return m

This code is going into endless loop.

   rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
  File "<pyshell#1>", line 7, in rr
    rr(z,m)
I tried dime a dozen  permutations oF the code.
Can some one show me  why it is going into Endless loop?

Thank you
Prasad

From anand.shashwat at gmail.com  Mon Jul  5 17:40:03 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Mon, 5 Jul 2010 21:10:03 +0530
Subject: [Tutor] raw_input
In-Reply-To: <AANLkTilwI4V7GkE1fCSrZ-0TiSLY6yaCsS2vjQbJI-f8@mail.gmail.com>
References: <AANLkTilwI4V7GkE1fCSrZ-0TiSLY6yaCsS2vjQbJI-f8@mail.gmail.com>
Message-ID: <AANLkTikwRdIaPsYzAq9o8pmSRR4KUo8jEvW0oXahdQKh@mail.gmail.com>

use input() instead of raw_input() in Python3.x

On Mon, Jul 5, 2010 at 8:50 PM, Dipo Elegbede <delegbede at dudupay.com> wrote:

> Hello,
>
> I seem to be having problems with raw_input.
>
> i wrote something like:
>
> raw_input('Press Enter')
>
> it comes back to tell me raw_input is not defined, a NameError!
>
> Is it that something about it has changed in python 3.1 or I have been
> writing the wrong thing.
>
> Please enlighten me.
>
> regards.
>
> --
> Elegbede Muhammed Oladipupo
> OCA
> +2348077682428
> +2347042171716
> www.dudupay.com
> Mobile Banking Solutions | Transaction Processing | Enterprise Application
> Development
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100705/546ff539/attachment-0001.html>

From delegbede at dudupay.com  Mon Jul  5 18:03:03 2010
From: delegbede at dudupay.com (Dipo Elegbede)
Date: Mon, 5 Jul 2010 17:03:03 +0100
Subject: [Tutor] raw_input
In-Reply-To: <AANLkTikwRdIaPsYzAq9o8pmSRR4KUo8jEvW0oXahdQKh@mail.gmail.com>
References: <AANLkTilwI4V7GkE1fCSrZ-0TiSLY6yaCsS2vjQbJI-f8@mail.gmail.com>
	<AANLkTikwRdIaPsYzAq9o8pmSRR4KUo8jEvW0oXahdQKh@mail.gmail.com>
Message-ID: <AANLkTilNl3N_WyGEqnVQtvMyhoQLG50lAHtsuIAUXoVX@mail.gmail.com>

Tried it out and it worked.
Thanks.
Regards,

On 7/5/10, Shashwat Anand <anand.shashwat at gmail.com> wrote:
> use input() instead of raw_input() in Python3.x
>
> On Mon, Jul 5, 2010 at 8:50 PM, Dipo Elegbede <delegbede at dudupay.com> wrote:
>
>> Hello,
>>
>> I seem to be having problems with raw_input.
>>
>> i wrote something like:
>>
>> raw_input('Press Enter')
>>
>> it comes back to tell me raw_input is not defined, a NameError!
>>
>> Is it that something about it has changed in python 3.1 or I have been
>> writing the wrong thing.
>>
>> Please enlighten me.
>>
>> regards.
>>
>> --
>> Elegbede Muhammed Oladipupo
>> OCA
>> +2348077682428
>> +2347042171716
>> www.dudupay.com
>> Mobile Banking Solutions | Transaction Processing | Enterprise Application
>> Development
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>

-- 
Sent from my mobile device

Elegbede Muhammed Oladipupo
OCA
+2348077682428
+2347042171716
www.dudupay.com
Mobile Banking Solutions | Transaction Processing | Enterprise
Application Development

From emile at fenx.com  Mon Jul  5 18:34:45 2010
From: emile at fenx.com (Emile van Sebille)
Date: Mon, 05 Jul 2010 09:34:45 -0700
Subject: [Tutor] endless loop
In-Reply-To: <AANLkTimhK_-NiOoSS48RCbKTSRouxDcka7MKrIhgKPJx@mail.gmail.com>
References: <AANLkTimhK_-NiOoSS48RCbKTSRouxDcka7MKrIhgKPJx@mail.gmail.com>
Message-ID: <i0t1iv$e7f$1@dough.gmane.org>

On 7/5/2010 8:31 AM prasad rao said...
> hi
>    I am trying problem 6 in projecteuler.org.
> What is the smallest positive number that is evenly divisible by all
> of the numbers from 1 to 20?
>
>
> def rr(z,m=1):
>            q=lambda n:m%n==0
>            s=lambda False : 0
>            a=filter(s,map(q,range(1,z)))
>            if not a:
>                m+=1
>                rr(z,m)
>            else:return m
>
> This code is going into endless loop.
>

You don't show us how you're invoking this function, but it seems to me 
the result of passing a terminally false function result (s is always 
false) into filter will always result in [] (so a is always false) and 
will thereby cause the else clause never to be reached.

Emile



From sander.sweers at gmail.com  Mon Jul  5 18:43:41 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Mon, 5 Jul 2010 18:43:41 +0200
Subject: [Tutor] raw_input
In-Reply-To: <AANLkTikwRdIaPsYzAq9o8pmSRR4KUo8jEvW0oXahdQKh@mail.gmail.com>
References: <AANLkTilwI4V7GkE1fCSrZ-0TiSLY6yaCsS2vjQbJI-f8@mail.gmail.com>
	<AANLkTikwRdIaPsYzAq9o8pmSRR4KUo8jEvW0oXahdQKh@mail.gmail.com>
Message-ID: <AANLkTinLxRWumkQUewna7VWx4dthFfa3DV8EOmV7Nu4J@mail.gmail.com>

On 5 July 2010 17:40, Shashwat Anand <anand.shashwat at gmail.com> wrote:
> use input() instead of raw_input() in Python3.x

To add to this, in Python 2 we had input() [1] (unsafe for most uses)
and raw_input() [2] (safe). Python 3 removed the old input() and
renamed raw_input() to input() [3,4].

Greets
Sander

[1] http://docs.python.org/library/functions.html#input
[2] http://docs.python.org/library/functions.html#raw_input
[3] http://docs.python.org/release/3.0.1/whatsnew/3.0.html#builtins
[4] http://www.python.org/dev/peps/pep-3111/

From eike.welk at gmx.net  Mon Jul  5 19:02:02 2010
From: eike.welk at gmx.net (Eike Welk)
Date: Mon, 5 Jul 2010 19:02:02 +0200
Subject: [Tutor] Running a python script as root.
In-Reply-To: <AANLkTilQ6EUdz7o5b7dIrcNM7YiSvaAROSw5MIVEdXe8@mail.gmail.com>
References: <AANLkTilQ6EUdz7o5b7dIrcNM7YiSvaAROSw5MIVEdXe8@mail.gmail.com>
Message-ID: <201007051902.02815.eike.welk@gmx.net>

Hello Srihari!

On Sunday July 4 2010 20:17:12 Srihari k wrote:
> I did #chmod +s settime.py so that SUID bit be set and all users can
> execute the script and set the system time.
> now the permissions of file are:
> -rwsr-xr-x 1 root root 165 2010-07-04 23:16 settime.py
> 
> 
> The script still works as before ..
> date: cannot set date: Operation not permitted
> Sun Jul  4 23:37:37 IST 2010

I think this is a security feature of the operating system: SUID root is 
ignored for scripts. Only compiled programs can (IMHO) be SUID root. 

I didn't know that this is true for Python, but Bash scripts can definitely 
not be SUID root. 


Eike.

From alan.gauld at btinternet.com  Mon Jul  5 19:36:46 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 5 Jul 2010 18:36:46 +0100
Subject: [Tutor] endless loop
References: <AANLkTimhK_-NiOoSS48RCbKTSRouxDcka7MKrIhgKPJx@mail.gmail.com>
Message-ID: <i0t579$qkm$1@dough.gmane.org>


"prasad rao" <prasadaraon50 at gmail.com> wrote


> def rr(z,m=1):
>          q=lambda n:m%n==0
>          s=lambda False : 0

This is always false???

>          a=filter(s,map(q,range(1,z)))

So this is always empty?

>          if not a:

So this is always true

>              m+=1
>              rr(z,m)

So you contuinuaslly call rr with the original z and an increasing m.
But nothing about m terminates the recursion, so it recurses 
forever - or until you hit the recursion limit.

>          else:return m

This is never executed

> This code is going into endless loop.

Yep, I'd say so.

> Can some one show me  why it is going into Endless loop?

Because you wrote iit that way. This is one reason recursion is hard,
you must make 100% certain that there is a terminatin condition that 
will somehow get you out again...

HTH,


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



From vineethrakesh at gmail.com  Mon Jul  5 19:54:55 2010
From: vineethrakesh at gmail.com (Vineeth Rakesh)
Date: Mon, 5 Jul 2010 13:54:55 -0400
Subject: [Tutor] Help return a pattern from list
Message-ID: <AANLkTimtfL0HdRJQrRZJxSyv8VeBwEHpvz_QDcJG4ftM@mail.gmail.com>

Hello all,

Can some one help me to return a special pattern from a list.

say list =
["something1.mp3","something2.mp3","something4.pdf","something5.odt"]

now say I just need to return the files with .mp3 extension. How to go about
doing this?

Thanks
Vin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100705/27bc9d96/attachment.html>

From sander.sweers at gmail.com  Mon Jul  5 20:19:21 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Mon, 5 Jul 2010 20:19:21 +0200
Subject: [Tutor] Help return a pattern from list
In-Reply-To: <AANLkTimtfL0HdRJQrRZJxSyv8VeBwEHpvz_QDcJG4ftM@mail.gmail.com>
References: <AANLkTimtfL0HdRJQrRZJxSyv8VeBwEHpvz_QDcJG4ftM@mail.gmail.com>
Message-ID: <AANLkTin00ML-zPjznWhwa7TQYlPyz6ULGAv8FW4ycpQ0@mail.gmail.com>

On 5 July 2010 19:54, Vineeth Rakesh <vineethrakesh at gmail.com> wrote:
> Can some one help me to return a special pattern from a list.
>
> say list =
> ["something1.mp3","something2.mp3","something4.pdf","something5.odt"]
>
> now say I just need to return the files with .mp3 extension. How to go about
> doing this?

Use os.path.splitext() to check for the extension and check if it
equals the extension you want. For example like below idle session:

>>> import os
>>> say_list = ["something1.mp3","something2.mp3","something4.pdf","something5.odt"]
>>> mp3_list = [x for x in say_list if os.path.splitext(x)[1].lower() == ".mp3"]
>>> mp3_list
['something1.mp3', 'something2.mp3']

Greets
Sander

From anand.shashwat at gmail.com  Mon Jul  5 20:28:38 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Mon, 5 Jul 2010 23:58:38 +0530
Subject: [Tutor] Help return a pattern from list
In-Reply-To: <AANLkTimtfL0HdRJQrRZJxSyv8VeBwEHpvz_QDcJG4ftM@mail.gmail.com>
References: <AANLkTimtfL0HdRJQrRZJxSyv8VeBwEHpvz_QDcJG4ftM@mail.gmail.com>
Message-ID: <AANLkTikC2PPBWdiw2ENsOuEDud9H0VNm_AdK_TmWsdyf@mail.gmail.com>

On Mon, Jul 5, 2010 at 11:24 PM, Vineeth Rakesh <vineethrakesh at gmail.com>wrote:

> Hello all,
>
> Can some one help me to return a special pattern from a list.
>
> say list =
> ["something1.mp3","something2.mp3","something4.pdf","something5.odt"]
>

One suggestion. Don't name a list as list. Use l or List or any other
variable name. list is one of the syntax in python.


>
> now say I just need to return the files with .mp3 extension. How to go
> about doing this?
>

>>> list =
["something1.mp3","something2.mp3","something4.pdf","something5.odt"]
>>> [i for i in list if i[-4:] == '.mp3']
['something1.mp3', 'something2.mp3']

or may be ,
>>> [i for i in list if os.path.splitext(i)[0] == '.mp3']  # If you want to
deal with file extentions, that is.
For smaller case string is good, for obscure patter, you can try regex
module.

 ~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100705/914abc94/attachment-0001.html>

From anand.shashwat at gmail.com  Mon Jul  5 20:29:55 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Mon, 5 Jul 2010 23:59:55 +0530
Subject: [Tutor] Help return a pattern from list
In-Reply-To: <AANLkTikC2PPBWdiw2ENsOuEDud9H0VNm_AdK_TmWsdyf@mail.gmail.com>
References: <AANLkTimtfL0HdRJQrRZJxSyv8VeBwEHpvz_QDcJG4ftM@mail.gmail.com> 
	<AANLkTikC2PPBWdiw2ENsOuEDud9H0VNm_AdK_TmWsdyf@mail.gmail.com>
Message-ID: <AANLkTimhaI76aYcItpoZEegjn2Uu0gs0C4F4xsrbgz6k@mail.gmail.com>

On Mon, Jul 5, 2010 at 11:58 PM, Shashwat Anand <anand.shashwat at gmail.com>wrote:

>
>
> On Mon, Jul 5, 2010 at 11:24 PM, Vineeth Rakesh <vineethrakesh at gmail.com>wrote:
>
>> Hello all,
>>
>> Can some one help me to return a special pattern from a list.
>>
>> say list =
>> ["something1.mp3","something2.mp3","something4.pdf","something5.odt"]
>>
>
> One suggestion. Don't name a list as list. Use l or List or any other
> variable name. list is one of the syntax in python.
>
>
>>
>> now say I just need to return the files with .mp3 extension. How to go
>> about doing this?
>>
>
> >>> list =
> ["something1.mp3","something2.mp3","something4.pdf","something5.odt"]
> >>> [i for i in list if i[-4:] == '.mp3']
> ['something1.mp3', 'something2.mp3']
>
> or may be ,
> >>> [i for i in list if os.path.splitext(i)[0] == '.mp3']  # If you want to
> deal with file extentions, that is.
>

Oops, sorry for the typo.
It'll be ,
>>> [i for i in list if os.path.splitext(i)[1] == '.mp3']


>  For smaller case string is good, for obscure patter, you can try regex
> module.
>
>  ~l0nwlf
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100705/7b0aa56b/attachment.html>

From schoappied at gmail.com  Mon Jul  5 23:59:14 2010
From: schoappied at gmail.com (Schoap D)
Date: Mon, 5 Jul 2010 23:59:14 +0200
Subject: [Tutor] the ball needs a kick...
Message-ID: <AANLkTimgf49FrIMxlg6x3NTpuP6-Rz8Wus2qS5PI_ZJo@mail.gmail.com>

Hi,

I'm doing the exercises here: chapter 8
http://www.openbookproject.net/thinkCSpy/ch08.html

Now I have added another paddle to the pong game. So far so good, but the
ball isn't moving anymore and I am not able to fix it...
Any comments, tips, feedback?

Thanks in advance,

http://paste.pocoo.org/show/233739/


Dirk
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100705/69708b4a/attachment.html>

From alan.gauld at btinternet.com  Tue Jul  6 01:19:02 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 6 Jul 2010 00:19:02 +0100
Subject: [Tutor] Help return a pattern from list
References: <AANLkTimtfL0HdRJQrRZJxSyv8VeBwEHpvz_QDcJG4ftM@mail.gmail.com>
	<AANLkTikC2PPBWdiw2ENsOuEDud9H0VNm_AdK_TmWsdyf@mail.gmail.com>
Message-ID: <i0tp91$u82$1@dough.gmane.org>


"Shashwat Anand" <anand.shashwat at gmail.com> wrote

>>>> list =
> ["something1.mp3","something2.mp3","something4.pdf","something5.odt"]
>>>> [i for i in list if i[-4:] == '.mp3']
> ['something1.mp3', 'something2.mp3']

Or even easier:

>>> [s for s in list if s.endswith('.mp3')]

But for the specific case of file extensions the os.path.splitext() is
a better solution.


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



From paradox at pobox.com  Tue Jul  6 01:40:28 2010
From: paradox at pobox.com (Thomas C. Hicks)
Date: Tue, 6 Jul 2010 07:40:28 +0800
Subject: [Tutor] Help return a pattern from list
In-Reply-To: <mailman.1020.1278354542.1671.tutor@python.org>
References: <mailman.1020.1278354542.1671.tutor@python.org>
Message-ID: <20100706074028.746e9005@midgel>

On Mon, 05 Jul 2010 20:29:02 +0200
tutor-request at python.org wrote:

> Date: Mon, 5 Jul 2010 13:54:55 -0400
> From: Vineeth Rakesh <vineethrakesh at gmail.com>
> To: tutor at python.org
> Subject: [Tutor] Help return a pattern from list
> Message-ID:
> 	<AANLkTimtfL0HdRJQrRZJxSyv8VeBwEHpvz_QDcJG4ftM at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> Hello all,
> 
> Can some one help me to return a special pattern from a list.
> 
> say list =
> ["something1.mp3","something2.mp3","something4.pdf","something5.odt"]
> 
> now say I just need to return the files with .mp3 extension. How to
> go about doing this?
> 
> Thanks
> Vin

I use the fnmatch module:

import fnmatch
fileList =
["something1.mp3","something2.mp3","something4.pdf","something5.odt"]
pattern='*.mp3'
for x in fnmatch.filter(fileList,pattern):
	#do something to your files or list items here

thomas

From emile at fenx.com  Tue Jul  6 02:46:24 2010
From: emile at fenx.com (Emile van Sebille)
Date: Mon, 05 Jul 2010 17:46:24 -0700
Subject: [Tutor] Help return a pattern from list
In-Reply-To: <i0tp91$u82$1@dough.gmane.org>
References: <AANLkTimtfL0HdRJQrRZJxSyv8VeBwEHpvz_QDcJG4ftM@mail.gmail.com>	<AANLkTikC2PPBWdiw2ENsOuEDud9H0VNm_AdK_TmWsdyf@mail.gmail.com>
	<i0tp91$u82$1@dough.gmane.org>
Message-ID: <i0tuco$9ou$1@dough.gmane.org>

On 7/5/2010 4:19 PM Alan Gauld said...

> But for the specific case of file extensions the os.path.splitext() is
> a better solution.
>
>


If, as the names suggest, the source is the file system, then I'd reach 
for glob.

Emile



From giseledjofang at cox.net  Mon Jul  5 15:52:44 2010
From: giseledjofang at cox.net (erinzo)
Date: Mon, 5 Jul 2010 06:52:44 -0700
Subject: [Tutor] I can't know how to use the "press the enter key to exit"
	command
Message-ID: <64F084E0E771438DB26C83E8B5606566@erinzoPC>

Sorry, I am a beginner in the python programming language.But went I type raw input("\n\npress the enter key to exit.") in the last line of the program,I have the syntaxerror.My program can not wait the user to press the enter key.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100705/369c0fda/attachment-0001.html>

From iamroot at ajilan.pair.com  Mon Jul  5 17:35:52 2010
From: iamroot at ajilan.pair.com (iamroot at ajilan.pair.com)
Date: Mon, 5 Jul 2010 11:35:52 -0400 (EDT)
Subject: [Tutor] raw_input
In-Reply-To: <AANLkTilwI4V7GkE1fCSrZ-0TiSLY6yaCsS2vjQbJI-f8@mail.gmail.com>
References: <AANLkTilwI4V7GkE1fCSrZ-0TiSLY6yaCsS2vjQbJI-f8@mail.gmail.com>
Message-ID: <alpine.BSF.2.00.1007051134380.14091@ajilan.pair.com>

On Mon, 5 Jul 2010, Dipo Elegbede wrote:

> Hello,
> 
> I seem to be having problems with raw_input.
> 
> i wrote something like:
> 
> raw_input('Press Enter')
> 
> it comes back to tell me raw_input is not defined, a NameError!
> 
> Is it that something about it has changed in python 3.1 or I have been writing the wrong thing.
> 
> Please enlighten me.
> 
> regards.
> 
> --
> Elegbede Muhammed Oladipupo
> OCA
> +2348077682428
> +2347042171716
> www.dudupay.com
> Mobile Banking Solutions | Transaction Processing | Enterprise Application Development
> 
> 
In Python 3, input has replaced raw_input.

This contains info about that and other things that have changed:

   http://www.ibm.com/developerworks/linux/library/l-python3-1/

From ilcomputertrasparente at gmail.com  Mon Jul  5 21:00:05 2010
From: ilcomputertrasparente at gmail.com (Francesco Loffredo)
Date: Mon, 05 Jul 2010 21:00:05 +0200
Subject: [Tutor] Tkinter mainloop()
Message-ID: <4C322BB5.1000106@libero.it>

Hello all, this is the first time I ask for advice but I've been lurking 
for some month and i'm sure I'll find more than I need.
I'm learning Python and Tkinter, and I chose an old board game as a 
practice field. I used a Canvas and many Polygons, one for each 
hexagonal space of the board, and I bound a mouse click to a PlacePiece 
function that handles the move. I managed to make it work for two human 
players, but when it came to let the computer play, I found a problem.
I made a slightly different function, called Auto_PlacePiece, that 
doesn't get the target hex from an Event, but from arguments given, and 
I had to figure when this function has to be called. I thought an 
obvious place is at the end of the move, whether it's a manual or auto 
one. Just after having switched from a player to the other, if the new 
current player is "COMPUTER" then an automatic move is triggered.
So, where's the problem? The problem is that the Canvas is refreshed, 
and the previous move becomes visible to the players, *only after the 
completion of the automatic move!* This is, I think, a consequence of 
the binding and a feature of Tk's mainloop(): the loop waits for the 
bound routine to end before redrawing the graphics, and unfortunately I 
call the automatic move inside (albeit at the very end) of the previous 
move. And now for the (long awaited) question:
How can I ask a Canvas to redraw itself at my command? And if i can't, 
when should I call the auto move?
TIA
Francesco

From alan.gauld at btinternet.com  Tue Jul  6 09:23:45 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 6 Jul 2010 08:23:45 +0100
Subject: [Tutor] I can't know how to use the "press the enter key to
	exit"command
References: <64F084E0E771438DB26C83E8B5606566@erinzoPC>
Message-ID: <i0ullt$o1$1@dough.gmane.org>


"erinzo" <giseledjofang at cox.net> wrote 

> Sorry, I am a beginner in the python programming language.
> But went I type raw input("\n\npress the enter key to exit.") 
> in the last line of the program,I have the syntaxerror.

If you are using Python v2 use

raw_input()      # note the underscore

If you are using Python v3 use

input()

HTH,


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





From camillo.pereira at gmail.com  Tue Jul  6 09:28:13 2010
From: camillo.pereira at gmail.com (Camillo Pereira)
Date: Tue, 6 Jul 2010 17:28:13 +1000
Subject: [Tutor] I can't know how to use the "press the enter key to
	exit" command
In-Reply-To: <AANLkTikJejlttC7e0NABWJ47D96tvDnKz4VJCOay57Dj@mail.gmail.com>
References: <64F084E0E771438DB26C83E8B5606566@erinzoPC>
	<AANLkTikJejlttC7e0NABWJ47D96tvDnKz4VJCOay57Dj@mail.gmail.com>
Message-ID: <AANLkTiloaOlmeQkAjVOv-5tEgEEGFb2jgq8hQMet-EF9@mail.gmail.com>

On 6 July 2010 17:27, Camillo Pereira <camillo.pereira at gmail.com> wrote:

> Hi,
>
> Can the error message be posted along with the Python code please.
>
> Regards,
>
> Camillo
>
> On 5 July 2010 23:52, erinzo <giseledjofang at cox.net> wrote:
>
>>  Sorry, I am a beginner in the python programming language.But went I
>> type raw input("\n\npress the enter key to exit.") in the last line of the
>> program,I have the syntaxerror.My program can not wait the user to press the
>> enter key.
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100706/c88840ae/attachment.html>

From beachkid at insightbb.com  Tue Jul  6 16:38:55 2010
From: beachkid at insightbb.com (Ken G.)
Date: Tue, 06 Jul 2010 10:38:55 -0400
Subject: [Tutor] Sorting the Dictionary Set?
Message-ID: <4C333FFF.2020203@insightbb.com>

Is there a way to sort a dictionary?

Assuming I have a dictionary set containing the following:

{'02': 1, '03': 1, '12': 1, '15': 2, '14': 2, '04': 3, '05': 1, '19': 1, 
'32': 1, '28': 1, '27': 1, '17': 2, '25': 1}

and using the following code:

     print ('Printing the result of numbers that are repeated:')
     print
     for x, y in counted.items():
         if y > 1:
             print "Number %s was found %s times." % (x,y)
         # else:
             # print "Number %s was found %s times." % (x,y)
     print

and the result are:

     Printing the result of numbers that are repeated:

     Number 15 was found 2 times.
     Number 14 was found 2 times.
     Number 04 was found 3 times.
     Number 17 was found 2 times.

and the question is:

How do I sort the dictionary so the numbers listed (15, 14, 04, 17) are 
listed in sorted ascending order such as:

Number 04 was found 3 times.
     Number 14 was found 2 times.
     Number 15 was found 2 times.
     Number 17 was found 2 times.

I would appreciate any help, suggestion or hint on how to do achieved 
the desired result.

Thanks,

Ken


From anand.shashwat at gmail.com  Tue Jul  6 16:50:37 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Tue, 6 Jul 2010 20:20:37 +0530
Subject: [Tutor] Sorting the Dictionary Set?
In-Reply-To: <4C333FFF.2020203@insightbb.com>
References: <4C333FFF.2020203@insightbb.com>
Message-ID: <AANLkTineO06KYPiJb3fillTvn1MHJTufnKE5aTMh3G6M@mail.gmail.com>

On Tue, Jul 6, 2010 at 8:08 PM, Ken G. <beachkid at insightbb.com> wrote:

> Is there a way to sort a dictionary?
>
> Assuming I have a dictionary set containing the following:
>
> {'02': 1, '03': 1, '12': 1, '15': 2, '14': 2, '04': 3, '05': 1, '19': 1,
> '32': 1, '28': 1, '27': 1, '17': 2, '25': 1}
>
> and using the following code:
>
>    print ('Printing the result of numbers that are repeated:')
>    print
>    for x, y in counted.items():
>        if y > 1:
>            print "Number %s was found %s times." % (x,y)
>        # else:
>            # print "Number %s was found %s times." % (x,y)
>    print
>
> and the result are:
>
>    Printing the result of numbers that are repeated:
>
>    Number 15 was found 2 times.
>    Number 14 was found 2 times.
>    Number 04 was found 3 times.
>    Number 17 was found 2 times.
>
> and the question is:
>
> How do I sort the dictionary so the numbers listed (15, 14, 04, 17) are
> listed in sorted ascending order such as:
>
> Number 04 was found 3 times.
>    Number 14 was found 2 times.
>    Number 15 was found 2 times.
>    Number 17 was found 2 times.
>

>>> d = {'02': 1, '03': 1, '12': 1, '15': 2, '14': 2, '04': 3, '05': 1,
'19': 1, '32': 1, '28': 1, '27': 1, '17': 2, '25': 1}
>>> import operator
>>> sorted(d.items(), key=operator.itemgetter(1), reverse = True)
[('04', 3), ('17', 2), ('15', 2), ('14', 2), ('25', 1), ('27', 1), ('02',
1), ('03', 1), ('12', 1), ('05', 1), ('19', 1), ('32', 1), ('28', 1)]

~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100706/9ee77d16/attachment.html>

From steve at pearwood.info  Tue Jul  6 16:58:52 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 7 Jul 2010 00:58:52 +1000
Subject: [Tutor] Sorting the Dictionary Set?
In-Reply-To: <4C333FFF.2020203@insightbb.com>
References: <4C333FFF.2020203@insightbb.com>
Message-ID: <201007070058.53327.steve@pearwood.info>

On Wed, 7 Jul 2010 12:38:55 am Ken G. wrote:
> Is there a way to sort a dictionary?

Not directly, dictionaries are unsorted and unsortable. They print in an 
arbitrary order.

If you need to operate on dictionaries in a specific, non-arbitrary 
order, you need to extract the keys, sort them, and then work from 
them. Example:

keys = mydict.keys()
keys.sort()
for key in keys:
    value = mydict[key]
    print "the value of key %s is %s" (key, value)

I'm sure you can adapt that example to what you're trying to do :)


-- 
Steven D'Aprano

From alan.gauld at btinternet.com  Tue Jul  6 17:32:10 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 6 Jul 2010 16:32:10 +0100
Subject: [Tutor] Tkinter mainloop()
References: <4C322BB5.1000106@libero.it>
Message-ID: <i0vi9m$8m0$1@dough.gmane.org>


"Francesco Loffredo" <ilcomputertrasparente at gmail.com> wrote

> How can I ask a Canvas to redraw itself at my command? And if i 
> can't, when should I call the auto move?

You can ask the canvas to repaint itself by calling 
update_idle_tasks()
method. But in general you shouldn't need to. It's usually better to 
keep
your event handlers short enough that they return to the mainloop 
which
will then redraw as necessary for you.

HTH,


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



From payal-python at scriptkitchen.com  Tue Jul  6 19:09:35 2010
From: payal-python at scriptkitchen.com (Payal)
Date: Tue, 6 Jul 2010 10:09:35 -0700
Subject: [Tutor] newbie to gui programming
Message-ID: <20100706170935.GA25974@scriptkitchen.com>

Hi all,
Some background before the actual query.
A friend of mine, an electronics engineer has a
small co. He had a computer engg. with him who used to design GUI
front-ends
for his products in Visual Basic. These apps used to take data from
serial port, store it on disk put and show it in excel also plot graphs. 
Now the engg has left. So my friend has asked me to help him out till 
he finds a replacement. I don't know a word of electronics and know Python to
extend of understanding almost 90% of "Learning Python" and 70-75% of
"Core Python programming" books.
Now my real query, do you think it is possible for me to try my hand at
gui programming? There seems to be many ways to do gui programming in
Python namely wxpython, tkinter, gtk, qt etc. Which is the easiest and
nice looking one and works on both windows and Linux? The interfaces
will be used by other electronics enggs. so they do not expect real
swell gui, but it should be bearable and more importantly easy for me to
learn, cos' I have a day time job and I am doing this just as a help and
eagerness to learn.
Looking  for advice.

Thanks a lot.
With warm regards,
-Payal
-- 




From davea at ieee.org  Tue Jul  6 19:45:27 2010
From: davea at ieee.org (Dave Angel)
Date: Tue, 06 Jul 2010 13:45:27 -0400
Subject: [Tutor] the ball needs a kick...
In-Reply-To: <AANLkTimgf49FrIMxlg6x3NTpuP6-Rz8Wus2qS5PI_ZJo@mail.gmail.com>
References: <AANLkTimgf49FrIMxlg6x3NTpuP6-Rz8Wus2qS5PI_ZJo@mail.gmail.com>
Message-ID: <4C336BB7.8030209@ieee.org>

Schoap D wrote:
> Hi,
>
> I'm doing the exercises here: chapter 8
> http://www.openbookproject.net/thinkCSpy/ch08.html
>
> Now I have added another paddle to the pong game. So far so good, but the
> ball isn't moving anymore and I am not able to fix it...
> Any comments, tips, feedback?
>
> Thanks in advance,
>
> http://paste.pocoo.org/show/233739/
>
>
> Dirk
>
>   
First thing to do is a file diff with the last version that worked 
properly.  You do that by going into your version control system.  
Chances are you made one more change than you realized you were making.

DaveA

From adam.jtm30 at gmail.com  Tue Jul  6 19:48:29 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Tue, 6 Jul 2010 18:48:29 +0100
Subject: [Tutor] newbie to gui programming
In-Reply-To: <20100706170935.GA25974@scriptkitchen.com>
References: <20100706170935.GA25974@scriptkitchen.com>
Message-ID: <AANLkTimPuPcpKk3w7brQPkx5_4YO9RSuGZ7TpPzVdXjB@mail.gmail.com>

On 6 July 2010 18:09, Payal <payal-python at scriptkitchen.com> wrote:

> Hi all,
> Some background before the actual query.
> A friend of mine, an electronics engineer has a
> small co. He had a computer engg. with him who used to design GUI
> front-ends
> for his products in Visual Basic. These apps used to take data from
> serial port, store it on disk put and show it in excel also plot graphs.
> Now the engg has left. So my friend has asked me to help him out till
> he finds a replacement. I don't know a word of electronics and know Python
> to
> extend of understanding almost 90% of "Learning Python" and 70-75% of
> "Core Python programming" books.
> Now my real query, do you think it is possible for me to try my hand at
> gui programming?


Of course you can, it depends on how complex the GUI has to be on how far
you'll get most likely.


> There seems to be many ways to do gui programming in
> Python namely wxpython, tkinter, gtk, qt etc. Which is the easiest and
> nice looking one and works on both windows and Linux?


Any of those toolkits are available on windows and linux, as to the nicest
looking, that's up to you and your friend to decide. wxPython does a good
job of blending in with other applications on the same system though.
Tkinter comes with python which may swing it for you.


> The interfaces
> will be used by other electronics enggs. so they do not expect real
> swell gui, but it should be bearable and more importantly easy for me to
> learn, cos' I have a day time job and I am doing this just as a help and
> eagerness to learn.
> Looking  for advice.
>
>
Once you've picked your toolkit you'll probably want to get on the relevant
mailing list to get some help.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100706/1c67a139/attachment-0001.html>

From alan.gauld at btinternet.com  Tue Jul  6 20:48:53 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 6 Jul 2010 19:48:53 +0100
Subject: [Tutor] newbie to gui programming
References: <20100706170935.GA25974@scriptkitchen.com>
Message-ID: <i0vtqh$plm$1@dough.gmane.org>

"Payal" <payal-python at scriptkitchen.com> wrote

> gui programming? There seems to be many ways to do gui programming 
> in
> Python namely wxpython, tkinter, gtk, qt etc. Which is the easiest

There are many toolkits but these have as many similarities as 
differences.
But none of them will be easy to learn if you have not done GUI work
before because GUI programming is a whole new style and that's what
takes the time. Once you learn one framework picking up another is
not that hard - just a lot of new API names to learn!

> nice looking one and works on both windows and Linux?

Nowadays they are all acceptable looking but wxPython would
be my recommendation, mainly for its support for printing, which
sounds easy but in Guis is surprisingly difficult. wxPython makes
it about as easy as it can be.

Don't underestimate the learning curve and use the toolset as much
as possible, also look at things like plotting libraries if you need 
to
display graphs etc.

You can compare very simple GUIs in Tkinter and wxPython
in the GUI topic of my tutor, and a slightly more complex
GUI in the Case Study topic.

HTH,

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



From ehamiter at gmail.com  Tue Jul  6 21:01:35 2010
From: ehamiter at gmail.com (Eric Hamiter)
Date: Tue, 6 Jul 2010 14:01:35 -0500
Subject: [Tutor] newbie to gui programming
In-Reply-To: <i0vtqh$plm$1@dough.gmane.org>
References: <20100706170935.GA25974@scriptkitchen.com>
	<i0vtqh$plm$1@dough.gmane.org>
Message-ID: <AANLkTik9ZNsakLhMsVTaPb7XLGOxw95MRvrhw2jruRXD@mail.gmail.com>

If you decide to run with wxPython there is a pretty handy video series you
could watch:

http://showmedo.com/videotutorials/series?name=PythonWxPythonBeginnersSeries

Eric


On Tue, Jul 6, 2010 at 1:48 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> "Payal" <payal-python at scriptkitchen.com> wrote
>
>  gui programming? There seems to be many ways to do gui programming in
>> Python namely wxpython, tkinter, gtk, qt etc. Which is the easiest
>>
>
> There are many toolkits but these have as many similarities as differences.
> But none of them will be easy to learn if you have not done GUI work
> before because GUI programming is a whole new style and that's what
> takes the time. Once you learn one framework picking up another is
> not that hard - just a lot of new API names to learn!
>
>
>  nice looking one and works on both windows and Linux?
>>
>
> Nowadays they are all acceptable looking but wxPython would
> be my recommendation, mainly for its support for printing, which
> sounds easy but in Guis is surprisingly difficult. wxPython makes
> it about as easy as it can be.
>
> Don't underestimate the learning curve and use the toolset as much
> as possible, also look at things like plotting libraries if you need to
> display graphs etc.
>
> You can compare very simple GUIs in Tkinter and wxPython
> in the GUI topic of my tutor, and a slightly more complex
> GUI in the Case Study topic.
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100706/4d680d09/attachment.html>

From airscorp at otenet.gr  Wed Jul  7 02:35:34 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Wed, 07 Jul 2010 03:35:34 +0300
Subject: [Tutor] newbie to gui programming
In-Reply-To: <i0vtqh$plm$1@dough.gmane.org>
References: <20100706170935.GA25974@scriptkitchen.com>
	<i0vtqh$plm$1@dough.gmane.org>
Message-ID: <4C33CBD6.6010206@otenet.gr>

Please excuse if I'm jumping on the topic. Haven't done any GUI work so 
this interests me too.

wxPython always seemed a great choice as it works on all platforms, and 
uses GTK+ for linux.
Well, what mainly bugs me about wxPython is that most of it's API names 
come from the wx C library, you almost can feel the C code underneath.
I would really love a more pythonic wrapper around it.

Really good news is that on this very list on another thread, someone 
suggested Dabo http://dabodev.com/
It's a python library on top of wxPython and it's database-logic-GUI 
separation looks a lot like the MVP of django, which I'm familiar with.

Of course, a bit not that easy to install if you're just starting out 
and there are no books for it. It's also database oriented, but I 
consider this a plus.

I'd like to hear your views on whether you think it might be a good 
choice for a new python programmer, exactly for the above reasons.
I think it might be worth the hurdles and pay off in the end.

Nick


On 07/06/2010 09:48 PM, Alan Gauld wrote:
> There are many toolkits but these have as many similarities as 
> differences.
> But none of them will be easy to learn if you have not done GUI work
> before because GUI programming is a whole new style and that's what
> takes the time. Once you learn one framework picking up another is
> not that hard - just a lot of new API names to learn!
>

From johnf at jfcomputer.com  Wed Jul  7 05:36:05 2010
From: johnf at jfcomputer.com (John)
Date: Tue, 6 Jul 2010 20:36:05 -0700
Subject: [Tutor] newbie to gui programming
In-Reply-To: <4C33CBD6.6010206@otenet.gr>
References: <20100706170935.GA25974@scriptkitchen.com>
	<i0vtqh$plm$1@dough.gmane.org> <4C33CBD6.6010206@otenet.gr>
Message-ID: <201007062036.05941.johnf@jfcomputer.com>

On Tuesday 06 July 2010 05:35:34 pm Nick Raptis wrote:
> Please excuse if I'm jumping on the topic. Haven't done any GUI work so
> this interests me too.
>
> wxPython always seemed a great choice as it works on all platforms, and
> uses GTK+ for linux.
> Well, what mainly bugs me about wxPython is that most of it's API names
> come from the wx C library, you almost can feel the C code underneath.
> I would really love a more pythonic wrapper around it.
>
> Really good news is that on this very list on another thread, someone
> suggested Dabo http://dabodev.com/
> It's a python library on top of wxPython and it's database-logic-GUI
> separation looks a lot like the MVP of django, which I'm familiar with.
>
> Of course, a bit not that easy to install if you're just starting out
> and there are no books for it. It's also database oriented, but I
> consider this a plus.
>
> I'd like to hear your views on whether you think it might be a good
> choice for a new python programmer, exactly for the above reasons.
> I think it might be worth the hurdles and pay off in the end.
>
> Nick

I really enjoy Dabo and I feel it is very easy to use and learn.  Best of all 
there plenty of support.

Johnf


From ilcomputertrasparente at gmail.com  Tue Jul  6 15:59:13 2010
From: ilcomputertrasparente at gmail.com (Francesco Loffredo)
Date: Tue, 06 Jul 2010 15:59:13 +0200
Subject: [Tutor] Tkinter mainloop()
In-Reply-To: <4C322BB5.1000106@libero.it>
References: <4C322BB5.1000106@libero.it>
Message-ID: <4C3336B1.5070305@libero.it>

RTFM.... I happened to find the answer just a couple of hours after 
having sent this message. How could I miss the update method of the Canvas?

Now my game works as expected, maybe I'll post it when it's complete.

Thanks to all!
Francesco

Il 05/07/2010 21.00, Francesco Loffredo ha scritto:
> Hello all, this is the first time I ask for advice but I've been lurking
> for some month and i'm sure I'll find more than I need.
> I'm learning Python and Tkinter, and I chose an old board game as a
> practice field. I used a Canvas and many Polygons, one for each
> hexagonal space of the board, and I bound a mouse click to a PlacePiece
> function that handles the move. I managed to make it work for two human
> players, but when it came to let the computer play, I found a problem.
> I made a slightly different function, called Auto_PlacePiece, that
> doesn't get the target hex from an Event, but from arguments given, and
> I had to figure when this function has to be called. I thought an
> obvious place is at the end of the move, whether it's a manual or auto
> one. Just after having switched from a player to the other, if the new
> current player is "COMPUTER" then an automatic move is triggered.
> So, where's the problem? The problem is that the Canvas is refreshed,
> and the previous move becomes visible to the players, *only after the
> completion of the automatic move!* This is, I think, a consequence of
> the binding and a feature of Tk's mainloop(): the loop waits for the
> bound routine to end before redrawing the graphics, and unfortunately I
> call the automatic move inside (albeit at the very end) of the previous
> move. And now for the (long awaited) question:
> How can I ask a Canvas to redraw itself at my command? And if i can't,
> when should I call the auto move?
> TIA
> Francesco
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
>
> Nessun virus nel messaggio in arrivo.
> Controllato da AVG - www.avg.com
> Versione: 9.0.830 / Database dei virus: 271.1.1/2984 -  Data di rilascio: 07/05/10 20:36:00
>

From ilcomputertrasparente at gmail.com  Tue Jul  6 18:02:24 2010
From: ilcomputertrasparente at gmail.com (Francesco Loffredo)
Date: Tue, 06 Jul 2010 18:02:24 +0200
Subject: [Tutor] Tkinter mainloop()
In-Reply-To: <i0vi9m$8m0$1@dough.gmane.org>
References: <4C322BB5.1000106@libero.it> <i0vi9m$8m0$1@dough.gmane.org>
Message-ID: <4C335390.2050409@libero.it>

Il 06/07/2010 17.32, Alan Gauld wrote:
>
> "Francesco Loffredo" <ilcomputertrasparente at gmail.com> wrote
>
>> How can I ask a Canvas to redraw itself at my command? And if i can't,
>> when should I call the auto move?
>
> You can ask the canvas to repaint itself by calling update_idle_tasks()
> method.
Thank you, Alan. As many answers, this poses me a new question: why 
should I call update_idle_tasks() instead of update() ? What's the 
difference between the two methods?

> But in general you shouldn't need to. It's usually better to keep
> your event handlers short enough that they return to the mainloop which
> will then redraw as necessary for you.
In general, I do agree. But I explained rather verbosely the peculiar 
situation I'm facing in my practice project: where would you put the 
automatic move call, if not where I did? I need an automatic move be 
performed at the proper moment, when it's the computer player turn.

> HTH,
   SID!  (sure it did!)

From alan.gauld at btinternet.com  Wed Jul  7 09:11:40 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 7 Jul 2010 08:11:40 +0100
Subject: [Tutor] Tkinter mainloop()
References: <4C322BB5.1000106@libero.it> <i0vi9m$8m0$1@dough.gmane.org>
	<4C335390.2050409@libero.it>
Message-ID: <i119b8$dg1$1@dough.gmane.org>


"Francesco Loffredo" <ilcomputertrasparente at gmail.com> wrote

>> You can ask the canvas to repaint itself by calling 
>> update_idle_tasks()
>> method.
> Thank you, Alan. As many answers, this poses me a new question: why 
> should I call update_idle_tasks() instead of update() ? What's the 
> difference between the two methods?

Its a little bit subtle but I believbe update() updates all widgets
whereas update_idle_tasks will only update those widgets that
have changed since the last update. In a complex GUI this can
be notably faster. Most of the books I've seen recommend not
using update() as it can cause race conditions but I have no 
experience
of that - because I use update_idle_tasks! :-)

>> But in general you shouldn't need to. It's usually better to keep
>> your event handlers short enough that they return to the mainloop 
>> which
>> will then redraw as necessary for you.
> In general, I do agree. But I explained rather verbosely the 
> peculiar situation I'm facing in my practice project: where would 
> you put the automatic move call, if not where I did? I need an 
> automatic move be performed at the proper moment, when it's the 
> computer player turn.

Create the auto move in an event handler of its own and associate
with an event. Then raise that event when your players move is 
finished.
Tkinter will then call the automove for you, updating the screeen
automatically. In an event driven environment control is passed
around by means of events.

How do you raise an event in Tkinter?
Use the event_generate() method.

Alternatively use the after() method with a short delay - say 10ms...

HTH,


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



From alan.gauld at btinternet.com  Wed Jul  7 09:16:28 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 7 Jul 2010 08:16:28 +0100
Subject: [Tutor] newbie to gui programming
References: <20100706170935.GA25974@scriptkitchen.com><i0vtqh$plm$1@dough.gmane.org>
	<4C33CBD6.6010206@otenet.gr>
Message-ID: <i119k8$ebm$1@dough.gmane.org>


"Nick Raptis" <airscorp at otenet.gr> wrote

> Really good news is that on this very list on another thread, 
> someone suggested Dabo http://dabodev.com/
> It's a python library on top of wxPython and it's database-logic-GUI

But its not a complete wrapper for wxPython so you still need
to revert to wxPython at some stages. Also its being database
centric is great if thats what you are doing, not so great for games
programming etc.

But the tight coupling of wxPython to its C++ roots can be seen
as a bonus because it means you can quickly use its Ruby and
Perl incarnations too - and if you need to the base C++.

This is one of the reasons I mainly use Tkinter - because I already
knew the underlying Tk and I can use those same skills in Lisp
and Ruby and Perl UI code.

You pays your money and makes your choice! :-)

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



From rdmoores at gmail.com  Wed Jul  7 10:03:56 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Wed, 7 Jul 2010 01:03:56 -0700
Subject: [Tutor] Does DreamPie work well?
Message-ID: <AANLkTimStBglVjrvDvE73nzVL_P09imIHS5PEfxoKQps@mail.gmail.com>

<http://dreampie.sourceforge.net/>

Thanks,

Dick Moores

From ajarncolin at gmail.com  Wed Jul  7 13:44:05 2010
From: ajarncolin at gmail.com (col speed)
Date: Wed, 7 Jul 2010 18:44:05 +0700
Subject: [Tutor] Problems with subtraction!
Message-ID: <AANLkTinrOWQGB069nWoMYmy2gsBzzy-LeMJzYl4-xzRi@mail.gmail.com>

I apologise in advance for such a silly question. Normally, I start to write
to the list and work the answer out before sending the mail. Not this time.
I'm trying to work out which triangles contain the cartesian origin (0, 0)
and have the following:

t = [-340, 495, -153, -910, 835, -947]
print  (0 - t[0])*(t[3] - t[1]) - (0 - t[1])*(t[2] - t[0])
print  (0 - t[4])*(t[3] - t[5]) - (0 - t[5])*(t[2] - t[4])
print  (0 - t[4])*(t[1] - t[5]) - (0 - t[5])*(t[0] - t[4])

where t is coordinates of triangle a,b,c and the maths is cross-product of
vectors - if all are negative then it contains the origin. Unfortunately,
when I run the programme, I get:

colin at colin-laptop:~/lib/python/euler$ python p102origin.py
-385135
904741
-91345

The second number should be negative ( I WANT it to be negative). For
example:

print  (0 - t[4])*(t[3] - t[5]) , (0 - t[5])*(t[2] - t[4])   gives :

-30895 -935636

And in the python shell:

>>> -30895 -935636
-966531

But:

print  (0 - t[4])*(t[3] - t[5]) <  (0 - t[5])*(t[2] - t[4])  gives :

False








>>> a = "No Error Message"
>>> b = "Correct Answer"
>>> a == b
False


Please forgive an old man a stupid question
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100707/c04dd9b3/attachment.html>

From evert.rol at gmail.com  Wed Jul  7 13:59:52 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 7 Jul 2010 13:59:52 +0200
Subject: [Tutor] Problems with subtraction!
In-Reply-To: <AANLkTinrOWQGB069nWoMYmy2gsBzzy-LeMJzYl4-xzRi@mail.gmail.com>
References: <AANLkTinrOWQGB069nWoMYmy2gsBzzy-LeMJzYl4-xzRi@mail.gmail.com>
Message-ID: <2C32F78A-70A3-4D35-BDB4-B4D77E00B1E1@gmail.com>

> The second number should be negative ( I WANT it to be negative). For example:
> 
> print  (0 - t[4])*(t[3] - t[5]) , (0 - t[5])*(t[2] - t[4])   gives : 
> 
> -30895 -935636
> 
> And in the python shell: 
> 
> >>> -30895 -935636
> -966531

No, because you have to *subtract* the second answer from the first ( according to your print statement: print  (0 - t[4])*(t[3] - t[5])  -  (0 - t[5])*(t[2] - t[4]) ). So:
>>> -30895 - -935636
904741


If you want it to be negative, check the order of your coordinates: maybe you need to interchange two variables between one set of parentheses. Or maybe you need to subtract absolute values instead (sorry, too lazy to do the math to find out what is correct).


From ajarncolin at gmail.com  Wed Jul  7 14:08:09 2010
From: ajarncolin at gmail.com (col speed)
Date: Wed, 7 Jul 2010 19:08:09 +0700
Subject: [Tutor] Problems with subtraction!
In-Reply-To: <2C32F78A-70A3-4D35-BDB4-B4D77E00B1E1@gmail.com>
References: <AANLkTinrOWQGB069nWoMYmy2gsBzzy-LeMJzYl4-xzRi@mail.gmail.com>
	<2C32F78A-70A3-4D35-BDB4-B4D77E00B1E1@gmail.com>
Message-ID: <AANLkTimnjg8x4iN5Jk0uSK3GHMToS1C7Ccj58-qBqm-y@mail.gmail.com>

On 7 July 2010 18:59, Evert Rol <evert.rol at gmail.com> wrote:

> > The second number should be negative ( I WANT it to be negative). For
> example:
> >
> > print  (0 - t[4])*(t[3] - t[5]) , (0 - t[5])*(t[2] - t[4])   gives :
> >
> > -30895 -935636
> >
> > And in the python shell:
> >
> > >>> -30895 -935636
> > -966531
>
> No, because you have to *subtract* the second answer from the first (
> according to your print statement: print  (0 - t[4])*(t[3] - t[5])  -  (0 -
> t[5])*(t[2] - t[4]) ). So:
> >>> -30895 - -935636
> 904741
>
>
> If you want it to be negative, check the order of your coordinates: maybe
> you need to interchange two variables between one set of parentheses. Or
> maybe you need to subtract absolute values instead (sorry, too lazy to do
> the math to find out what is correct).
>

Yes, it's so simple isn't it? The old double negative. Thanks a lot for your
prompt reply, great.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100707/8b1f2352/attachment.html>

From airscorp at otenet.gr  Wed Jul  7 15:30:22 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Wed, 07 Jul 2010 16:30:22 +0300
Subject: [Tutor] newbie to gui programming
In-Reply-To: <i119k8$ebm$1@dough.gmane.org>
References: <20100706170935.GA25974@scriptkitchen.com><i0vtqh$plm$1@dough.gmane.org>	<4C33CBD6.6010206@otenet.gr>
	<i119k8$ebm$1@dough.gmane.org>
Message-ID: <4C34816E.5030504@otenet.gr>

Well, choice is a great thing!
Except when you're new and all that choice seems overwhelming :)

When I started out python a year ago, I knew just enough C to know that 
I didn't want C/C++ to be my first language that I learned.
That's why I found the wxPython style a nuisance, because I was at the 
same time trying to learn the python way of doing things.
I do see the merits you say in how wxPython does things, it just didn't 
work out then.
In the end, I never did any GUI work because of the overwhelming choice 
and instead did a little pygame stuff and then got into django, mostlly 
because my local community did.
So, db-centric seems good to me right now and will definately check dabo 
out, although to be honest, a webkit application on top of django sounds 
as good.

Anyways, I'm drifting all this while away from the purpose of this list.
Thank you so much for the answers, you're such a helpful bunch.

Nick

On 07/07/2010 10:16 AM, Alan Gauld wrote:
>
> "Nick Raptis" <airscorp at otenet.gr> wrote
>
>> Really good news is that on this very list on another thread, someone 
>> suggested Dabo http://dabodev.com/
>> It's a python library on top of wxPython and it's database-logic-GUI
>
> But its not a complete wrapper for wxPython so you still need
> to revert to wxPython at some stages. Also its being database
> centric is great if thats what you are doing, not so great for games
> programming etc.
>
> But the tight coupling of wxPython to its C++ roots can be seen
> as a bonus because it means you can quickly use its Ruby and
> Perl incarnations too - and if you need to the base C++.
>
> This is one of the reasons I mainly use Tkinter - because I already
> knew the underlying Tk and I can use those same skills in Lisp
> and Ruby and Perl UI code.
>
> You pays your money and makes your choice! :-)
>

From eduardo.susan at gmail.com  Thu Jul  8 00:52:12 2010
From: eduardo.susan at gmail.com (Eduardo Vieira)
Date: Wed, 7 Jul 2010 16:52:12 -0600
Subject: [Tutor] differences between mmap and StringIO
Message-ID: <AANLkTilAFguUe5FOYDaJXTZafuQS-4iouMDD4HroNZZe@mail.gmail.com>

Hello, I'm getting confused about the usage of those 2 modules. Which
should I use one to get/manipulate data from a text file?

Regards,

Eduardo
www.express-sign-supply.com

From airscorp at otenet.gr  Thu Jul  8 03:45:13 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Thu, 08 Jul 2010 04:45:13 +0300
Subject: [Tutor] differences between mmap and StringIO
In-Reply-To: <AANLkTilAFguUe5FOYDaJXTZafuQS-4iouMDD4HroNZZe@mail.gmail.com>
References: <AANLkTilAFguUe5FOYDaJXTZafuQS-4iouMDD4HroNZZe@mail.gmail.com>
Message-ID: <4C352DA9.6050905@otenet.gr>

Actually, for simple file operations I'd neither.
Standard file usage is described here, if you haven't checked it out, 
which I'm sure you have 
http://docs.python.org/library/stdtypes.html#file-objects

StringIO is useful as a buffer. That is, you make a file-like object in 
memory with StringIO, manipulate it as a file, and can then copy it to a 
real file with standard file operations. Really really useful for very 
intensive file operations. Pdf creation comes in mind.

mmap... Well I didn't even know it existed until you mentioned it! Seems 
to be an advanced method of reading a file in memory and manipulating it 
from there with choice of whether it actually affects the physical file 
or not. It's help page says it is also used for communicating with 
subprocesses.. wow! You definately won't need that :)

Anyway, files, StringIOs and mmaps are file-like objects, which means 
they have the same methods and functionality, so you know how to use 
one, you know them all from this aspect.

My recommendation would be, either manipulate a file directly which is 
fine for most cases.

Or if you really want to:
open your file for reading, make a StringIO instance, copy your file to 
it, close the file,
do whatever you want in memory,
open your file again for writing, copy the StringIO to it, close both.
I'd consider that overkill for most projects

Is there something in particular you want to do?

Nick

On 07/08/2010 01:52 AM, Eduardo Vieira wrote:
> Hello, I'm getting confused about the usage of those 2 modules. Which
> should I use one to get/manipulate data from a text file?
>
> Regards,
>
> Eduardo
> www.express-sign-supply.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
>    

From payal-python at scriptkitchen.com  Thu Jul  8 13:15:29 2010
From: payal-python at scriptkitchen.com (Payal)
Date: Thu, 8 Jul 2010 04:15:29 -0700
Subject: [Tutor] newbie to gui programming
In-Reply-To: <i0vtqh$plm$1@dough.gmane.org>
References: <20100706170935.GA25974@scriptkitchen.com>
	<i0vtqh$plm$1@dough.gmane.org>
Message-ID: <20100708111529.GA304@scriptkitchen.com>

On Tue, Jul 06, 2010 at 07:48:53PM +0100, Alan Gauld wrote:
> Nowadays they are all acceptable looking but wxPython would
> be my recommendation, mainly for its support for printing, which
> sounds easy but in Guis is surprisingly difficult. wxPython makes
> it about as easy as it can be.
>

Thanks a lot for the mails all of you.
Someone commented that wxpython occassionally shows it C/C++ roots. Will
that haunt me cos' I have zero knowledge of C/C++.

What about py-gtk? Is it more pythonic to learn and hence easy?
Or can I start with tkinter (and maybe remain with it), if it is easy to
learn? (I liked fetchmailconf and I think it was done in tkinter).

I get discouraged a bit fast, so I want the first toolset to be as easy
as possible.

With warm regards,
-Payal
-- 


From noufal at nibrahim.net.in  Thu Jul  8 13:32:04 2010
From: noufal at nibrahim.net.in (Noufal Ibrahim)
Date: Thu, 08 Jul 2010 17:02:04 +0530
Subject: [Tutor] newbie to gui programming
In-Reply-To: <20100708111529.GA304@scriptkitchen.com> (Payal's message of
	"Thu, 8 Jul 2010 04:15:29 -0700")
References: <20100706170935.GA25974@scriptkitchen.com>
	<i0vtqh$plm$1@dough.gmane.org>
	<20100708111529.GA304@scriptkitchen.com>
Message-ID: <878w5mjjkb.fsf@nibrahim.net.in>

Payal <payal-python at scriptkitchen.com> writes:

[...]

> Thanks a lot for the mails all of you.
> Someone commented that wxpython occassionally shows it C/C++ roots. Will
> that haunt me cos' I have zero knowledge of C/C++.
>
> What about py-gtk? Is it more pythonic to learn and hence easy?

I've used wx and pygtk and don't really have a recommendation one way or
another. But then again, my use was quite light. I do know though that
wx is a lot more first class on platforms other than Gnu/Linux.

> Or can I start with tkinter (and maybe remain with it), if it is easy to
> learn? (I liked fetchmailconf and I think it was done in tkinter).

Tkinter is nice for quick and dirty throw away stuff. I wouldn't
recommend it for any large apps but if you want to get your feet wet,
it's a nice thing to try out. 

> I get discouraged a bit fast, so I want the first toolset to be as
> easy as possible.

Tkinter is good on that front but it can quickly get out of control for
larger apps. 

[...]


-- 
~noufal
http://nibrahim.net.in

From airscorp at otenet.gr  Thu Jul  8 14:20:36 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Thu, 08 Jul 2010 15:20:36 +0300
Subject: [Tutor] newbie to gui programming
In-Reply-To: <20100708111529.GA304@scriptkitchen.com>
References: <20100706170935.GA25974@scriptkitchen.com>	<i0vtqh$plm$1@dough.gmane.org>
	<20100708111529.GA304@scriptkitchen.com>
Message-ID: <4C35C294.1070701@otenet.gr>

Thanks a lot for the mails all of you.
> Someone commented that wxpython occassionally shows it C/C++ roots. Will
> that haunt me cos' I have zero knowledge of C/C++.
>    
That would be me, sorry about that, didn't mean to confuse you further. 
Well, think it this way, if you have zero knowledge of C, you won't even 
notice.

> What about py-gtk? Is it more pythonic to learn and hence easy?
>    
Not really, every library shows it's roots every now and then.
> Or can I start with tkinter (and maybe remain with it), if it is easy to
> learn? (I liked fetchmailconf and I think it was done in tkinter).
>    
It comes bundled with python, is easy for easy tasks but 'might' be a 
burden as you scale up your projects. Why not?
> I get discouraged a bit fast, so I want the first toolset to be as easy
> as possible.
>
> With warm regards,
> -Payal
>    

Well I can relate to that. Was not so long ago when all choice seemed 
overwhelming and I thought that I better learn the best language/library 
from the start or I'll be wasting time.
Truth is, it doesn't really matter this much. Start with one, anyone and 
for whatever reason (eg, you found a book for it) and go for it for a 
week. If it doesn't work for you, you'll know by then, and not a lot of 
energy got wasted.
GUI programming is hard cause there a lot of new concepts to learn. 
Learning those concepts so you can apply them to any library should be 
your goal.

Anyway, my personal story is that after trying wxPython with a book a 
bit I decided that GUI programming was not my thing at all, and started 
writing games with pygame. Many similar concepts, twice the fun. Now I'm 
doing web work.

Give it time, trust your gut and don't panic, you'll end up right where 
you want :)
Nick

From delegbede at dudupay.com  Thu Jul  8 14:48:30 2010
From: delegbede at dudupay.com (Dipo Elegbede)
Date: Thu, 8 Jul 2010 13:48:30 +0100
Subject: [Tutor] Django Read
Message-ID: <AANLkTimIK93xqB1dQVRTpeOyx1WLxnfDrtzYml-mQUHP@mail.gmail.com>

Hi all,

I have done a little basic on python and have to start working on a
major django platform.
I'm starting new and would like recommendations on books I can read.

Kindly help me out. I want to get my hands dirty as fast as I can so
that I can be part of the project.

Thanks and Best regards,

-- 
Sent from my mobile device

Elegbede Muhammed Oladipupo
OCA
+2348077682428
+2347042171716
www.dudupay.com
Mobile Banking Solutions | Transaction Processing | Enterprise
Application Development

From zstumgoren at gmail.com  Thu Jul  8 15:01:55 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Thu, 8 Jul 2010 09:01:55 -0400
Subject: [Tutor] Django Read
In-Reply-To: <AANLkTimIK93xqB1dQVRTpeOyx1WLxnfDrtzYml-mQUHP@mail.gmail.com>
References: <AANLkTimIK93xqB1dQVRTpeOyx1WLxnfDrtzYml-mQUHP@mail.gmail.com>
Message-ID: <AANLkTikfJGc5SD4TCKtRYK6eXbXiFJe_XvsC1AO-wuK6@mail.gmail.com>

Python Web Development With Django has a good primer on Python (in general
and as it relates Django), along with a nice sampling of projects (creating
a basic CMS, using Ajax in an application, creating a Pastebin site).

You can learn about Django best practices and get a taste for some related
tools (Fabric, pip/virtualenv) by reading James Bennett's Practical Django
Projects, 2nd Edition.

And of course, don't forget the Django docs. They have a great starter
tutorial that walks you through the basics, and plenty of documentation on
the various features of the framework.

http://www.djangoproject.com/

HTH,
Serdar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100708/c9d98f58/attachment.html>

From airscorp at otenet.gr  Thu Jul  8 15:06:19 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Thu, 08 Jul 2010 16:06:19 +0300
Subject: [Tutor] Django Read
In-Reply-To: <AANLkTimIK93xqB1dQVRTpeOyx1WLxnfDrtzYml-mQUHP@mail.gmail.com>
References: <AANLkTimIK93xqB1dQVRTpeOyx1WLxnfDrtzYml-mQUHP@mail.gmail.com>
Message-ID: <4C35CD4B.2080603@otenet.gr>

There actually aren't that many books on django around yet which is a pity.
You should definitely read "The django book": 
http://www.djangobook.com/en/2.0/
either on the online version on that link, or it's printed counterpart 
(yes, it's really the same book): 
http://www.amazon.com/Definitive-Guide-Django-Development-Second/dp/143021936X/

The printed one is a bit more updated (1.1) and pays off it's money 
because of it's great reference section :)

Nick

On 07/08/2010 03:48 PM, Dipo Elegbede wrote:
> Hi all,
>
> I have done a little basic on python and have to start working on a
> major django platform.
> I'm starting new and would like recommendations on books I can read.
>
> Kindly help me out. I want to get my hands dirty as fast as I can so
> that I can be part of the project.
>
> Thanks and Best regards,
>
>    

From pvangundy at rez1.com  Thu Jul  8 15:04:54 2010
From: pvangundy at rez1.com (Paul VanGundy)
Date: Thu, 8 Jul 2010 09:04:54 -0400
Subject: [Tutor] Having a return when subprocess.Popen finishes
Message-ID: <1278594294.11905.4.camel@bluematter>

Hi All,

I'm trying to get data from subprocess.Popen. To be specific, I am
trying to read a ping echo and take the output and assign it to a
variable like below:

ping = subprocess.Popen("ping -c 5 %s" % (server),
stdout=subprocess.PIPE, shell=True)

However, when I run the command the output that gets assigned to my ping
variable is something along the lines of '<subprocess.Popen object at
0x9524bec>' and am not returned to >>> prompt. I know that is the proper
output but I need to be able to capture the ping replies and assign
those to a variable. I tried adding a \r and \n at the end of my cmd.
Any help would be greatly appreciated. I'm open to improvements,
different ways of doing it and corrections. :) If more info is needed
let me know. Thanks.

/paul

From jeff at dcsoftware.com  Thu Jul  8 15:31:35 2010
From: jeff at dcsoftware.com (Jeff Johnson)
Date: Thu, 08 Jul 2010 06:31:35 -0700
Subject: [Tutor] Django Read
In-Reply-To: <4C35CD4B.2080603@otenet.gr>
References: <AANLkTimIK93xqB1dQVRTpeOyx1WLxnfDrtzYml-mQUHP@mail.gmail.com>
	<4C35CD4B.2080603@otenet.gr>
Message-ID: <4C35D337.8070405@dcsoftware.com>

On 07/08/2010 06:06 AM, Nick Raptis wrote:
> There actually aren't that many books on django around yet which is a 
> pity.
> You should definitely read "The django book": 
> http://www.djangobook.com/en/2.0/
> either on the online version on that link, or it's printed counterpart 
> (yes, it's really the same book): 
> http://www.amazon.com/Definitive-Guide-Django-Development-Second/dp/143021936X/ 
>
>
> The printed one is a bit more updated (1.1) and pays off it's money 
> because of it's great reference section :)
>
> Nick
>
> On 07/08/2010 03:48 PM, Dipo Elegbede wrote:
>> Hi all,
>>
>> I have done a little basic on python and have to start working on a
>> major django platform.
>> I'm starting new and would like recommendations on books I can read.
>>
>> Kindly help me out. I want to get my hands dirty as fast as I can so
>> that I can be part of the project.
>>
>> Thanks and Best regards,
>>
>
I have six books on my bookshelf for Django.  There are others I don't 
have.  Django 1.0 Template Development is my favorite.  Many of them 
walk you through building apps step by step.  Do a search on Amazon.  
That is where I got most of them.

-- 
Jeff

-------------------

Jeff Johnson
jeff at dcsoftware.com




From airscorp at otenet.gr  Thu Jul  8 15:33:02 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Thu, 08 Jul 2010 16:33:02 +0300
Subject: [Tutor] Having a return when subprocess.Popen finishes
In-Reply-To: <1278594294.11905.4.camel@bluematter>
References: <1278594294.11905.4.camel@bluematter>
Message-ID: <4C35D38E.4090904@otenet.gr>

subprocess.Popen is a class, and as such it returns an object which can 
do a lot of stuff besides just reading the output.

What you want to do here is using it's communicate() method as such:

output, errors = ping.communicate()


Also, there is a quicker way, I think from version 2.7 forward: use  the 
shortcut
output = subprocess.check_output("your command here")

Always check latest documentation for your python version too
http://docs.python.org/library/subprocess.html

Nick

On 07/08/2010 04:04 PM, Paul VanGundy wrote:
> Hi All,
>
> I'm trying to get data from subprocess.Popen. To be specific, I am
> trying to read a ping echo and take the output and assign it to a
> variable like below:
>
> ping = subprocess.Popen("ping -c 5 %s" % (server),
> stdout=subprocess.PIPE, shell=True)
>
> However, when I run the command the output that gets assigned to my ping
> variable is something along the lines of '<subprocess.Popen object at
> 0x9524bec>' and am not returned to>>>  prompt. I know that is the proper
> output but I need to be able to capture the ping replies and assign
> those to a variable. I tried adding a \r and \n at the end of my cmd.
> Any help would be greatly appreciated. I'm open to improvements,
> different ways of doing it and corrections. :) If more info is needed
> let me know. Thanks.
>
> /paul
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
>    

From payal-python at scriptkitchen.com  Thu Jul  8 15:39:51 2010
From: payal-python at scriptkitchen.com (Payal)
Date: Thu, 8 Jul 2010 06:39:51 -0700
Subject: [Tutor] Having a return when subprocess.Popen finishes
In-Reply-To: <1278594294.11905.4.camel@bluematter>
References: <1278594294.11905.4.camel@bluematter>
Message-ID: <20100708133951.GA4572@scriptkitchen.com>

On Thu, Jul 08, 2010 at 09:04:54AM -0400, Paul VanGundy wrote:
> Hi All,
> 
> I'm trying to get data from subprocess.Popen. To be specific, I am
> trying to read a ping echo and take the output and assign it to a
> variable like below:
> 
> ping = subprocess.Popen("ping -c 5 %s" % (server),
> stdout=subprocess.PIPE, shell=True)

>>> import subprocess
>>> server = 'localhost'
>>> ping = subprocess.Popen("ping -c 5 %s" %
>>> (server),stdout=subprocess.PIPE, shell=True)
>>> ping.communicate()
('PING localhost (127.0.0.1) 56(84) bytes of data.\n64 bytes from
localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.044 ms\n64 bytes from
localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.046 ms\n64 bytes from
localhost (127.0.0.1): icmp_seq=3 ttl=64 time=0.052 ms\n64 bytes from
localhost (127.0.0.1): icmp_seq=4 ttl=64 time=0.046 ms\n64 bytes from
localhost (127.0.0.1): icmp_seq=5 ttl=64 time=0.049 ms\n\n--- localhost
ping statistics ---\n5 packets transmitted, 5 received, 0% packet loss,
time 3997ms\nrtt min/avg/max/mdev = 0.044/0.047/0.052/0.006 ms\n', None)
>>>

hth,
With warm regards,
-Payal
-- 


From huyslogic at gmail.com  Thu Jul  8 16:19:38 2010
From: huyslogic at gmail.com (Huy Ton That)
Date: Thu, 8 Jul 2010 10:19:38 -0400
Subject: [Tutor] Django Read
In-Reply-To: <4C35D337.8070405@dcsoftware.com>
References: <AANLkTimIK93xqB1dQVRTpeOyx1WLxnfDrtzYml-mQUHP@mail.gmail.com> 
	<4C35CD4B.2080603@otenet.gr> <4C35D337.8070405@dcsoftware.com>
Message-ID: <AANLkTik4qWUfiMJC3-gR4y4WX36PKHUIAyjbpT-lm7B9@mail.gmail.com>

I've went through the djangobook myself, and found it quite readable. This
would be my recommendation as well.

Be sure to read the sidebar comments; if you ever feel stuck, someone else
may have addressed the question/answer for you!

-Lee

On Thu, Jul 8, 2010 at 9:31 AM, Jeff Johnson <jeff at dcsoftware.com> wrote:

> On 07/08/2010 06:06 AM, Nick Raptis wrote:
>
>> There actually aren't that many books on django around yet which is a
>> pity.
>> You should definitely read "The django book":
>> http://www.djangobook.com/en/2.0/
>> either on the online version on that link, or it's printed counterpart
>> (yes, it's really the same book):
>> http://www.amazon.com/Definitive-Guide-Django-Development-Second/dp/143021936X/
>>
>> The printed one is a bit more updated (1.1) and pays off it's money
>> because of it's great reference section :)
>>
>> Nick
>>
>> On 07/08/2010 03:48 PM, Dipo Elegbede wrote:
>>
>>> Hi all,
>>>
>>> I have done a little basic on python and have to start working on a
>>> major django platform.
>>> I'm starting new and would like recommendations on books I can read.
>>>
>>> Kindly help me out. I want to get my hands dirty as fast as I can so
>>> that I can be part of the project.
>>>
>>> Thanks and Best regards,
>>>
>>>
>>  I have six books on my bookshelf for Django.  There are others I don't
> have.  Django 1.0 Template Development is my favorite.  Many of them walk
> you through building apps step by step.  Do a search on Amazon.  That is
> where I got most of them.
>
> --
> Jeff
>
> -------------------
>
> Jeff Johnson
> jeff at dcsoftware.com
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100708/ebcdec1c/attachment.html>

From g.nius.ck at gmail.com  Fri Jul  9 00:39:33 2010
From: g.nius.ck at gmail.com (Christopher King)
Date: Thu, 8 Jul 2010 18:39:33 -0400
Subject: [Tutor] differences between mmap and StringIO
In-Reply-To: <AANLkTilAFguUe5FOYDaJXTZafuQS-4iouMDD4HroNZZe@mail.gmail.com>
References: <AANLkTilAFguUe5FOYDaJXTZafuQS-4iouMDD4HroNZZe@mail.gmail.com>
Message-ID: <AANLkTin1YIBQ5BIOoZu95NYLv_FGRcVuWRHWtHkPnZbf@mail.gmail.com>

Well, I would just use the builting function open. I think Nick said in the
beggining. Or, I would use the module I created. It's a file object, with
the property file_txt. Unlike the other modules which you have to use read
and write methods, I made a method which allows you to manulipulate like a
string. I didn't even add a appending feature, but doing file.file_txt +=
'bla', you can append. I can send it to you if you like.

On Wed, Jul 7, 2010 at 6:52 PM, Eduardo Vieira <eduardo.susan at gmail.com>wrote:

> Hello, I'm getting confused about the usage of those 2 modules. Which
> should I use one to get/manipulate data from a text file?
>
> Regards,
>
> Eduardo
> www.express-sign-supply.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100708/45f9c016/attachment.html>

From ilcomputertrasparente at gmail.com  Thu Jul  8 20:40:36 2010
From: ilcomputertrasparente at gmail.com (Francesco Loffredo)
Date: Thu, 08 Jul 2010 20:40:36 +0200
Subject: [Tutor] Tkinter mainloop()
In-Reply-To: <i119b8$dg1$1@dough.gmane.org>
References: <4C322BB5.1000106@libero.it>
	<i0vi9m$8m0$1@dough.gmane.org>	<4C335390.2050409@libero.it>
	<i119b8$dg1$1@dough.gmane.org>
Message-ID: <4C361BA4.4050002@libero.it>



Il 07/07/2010 9.11, Alan Gauld wrote:
>
> "Francesco Loffredo" <ilcomputertrasparente at gmail.com> wrote
>
>> ... What's the
>> difference between the two methods?
>
> Its a little bit subtle but I believbe update() updates all widgets
> whereas update_idle_tasks will only update those widgets that
> have changed since the last update. In a complex GUI this can
> be notably faster. Most of the books I've seen recommend not
> using update() as it can cause race conditions but I have no experience
> of that - because I use update_idle_tasks! :-)

Ok, now I'm using update_idletasks() too (update_idle_tasks() doesn't 
exist) and I like it. Thanks a lot!

> ...

>> where would you put the
>> automatic move call, if not where I did? I need an automatic move be
>> performed at the proper moment, when it's the computer player turn.
>
> Create the auto move in an event handler of its own and associate
> with an event. Then raise that event when your players move is finished.
> Tkinter will then call the automove for you, updating the screeen
> automatically. In an event driven environment control is passed
> around by means of events.
I prefer not to make this project fully event driven, because while it's 
fairly easy to translate a mouse click into the game coordinates of the 
hex that's being clicked, I don't like translating a pair of integers to 
some point (maybe the center) of an hexagon, creating an Event 
structure, raising that Event and handling it, just to figure out...the 
same couple of integers I started with. No, I prefer not to create fake 
Events when there's none involved... at least in this little game. I'll 
remember your advice for some serious project!
>
> How do you raise an event in Tkinter?
> Use the event_generate() method.
And this would have been my next question, thanks for mind-reading!
>
> Alternatively use the after() method with a short delay - say 10ms...
That's what I actually did. It plays like a charm! THANK YOU!
>
> HTH,
   SID!

Francesco

From grigor.kolev at gmail.com  Fri Jul  9 10:20:13 2010
From: grigor.kolev at gmail.com (=?windows-1251?B?w/Do4+7w?=)
Date: Fri, 9 Jul 2010 11:20:13 +0300
Subject: [Tutor] Video card test
Message-ID: <AANLkTinPecYQOrp9U1j9Hygu0m6Qvs9itU0_bDwB0If5@mail.gmail.com>

Which module can I use to do a script for testing video card

-- 
????? ???? ???? ???, ???? ???? ??????? ?? ???? ?? ???? !

From steve at pearwood.info  Fri Jul  9 11:31:52 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 9 Jul 2010 19:31:52 +1000
Subject: [Tutor] Video card test
In-Reply-To: <AANLkTinPecYQOrp9U1j9Hygu0m6Qvs9itU0_bDwB0If5@mail.gmail.com>
References: <AANLkTinPecYQOrp9U1j9Hygu0m6Qvs9itU0_bDwB0If5@mail.gmail.com>
Message-ID: <201007091931.52482.steve@pearwood.info>

On Fri, 9 Jul 2010 06:20:13 pm ?????? wrote:
> Which module can I use to do a script for testing video card

Tell us how you want to test the video card.


-- 
Steven D'Aprano

From edwardlang at optonline.net  Fri Jul  9 13:21:54 2010
From: edwardlang at optonline.net (Edward Lang)
Date: Fri, 09 Jul 2010 07:21:54 -0400
Subject: [Tutor] Tutor Digest, Vol 77, Issue 25
Message-ID: <s38uw3ob7m0202pkgaaja08u.1278674514648@email.android.com>



tutor-request at python.org wrote:

>Send Tutor mailing list submissions to
>	tutor at python.org
>
>To subscribe or unsubscribe via the World Wide Web, visit
>	http://mail.python.org/mailman/listinfo/tutor
>or, via email, send a message with subject or body 'help' to
>	tutor-request at python.org
>
>You can reach the person managing the list at
>	tutor-owner at python.org
>
>When replying, please edit your Subject line so it is more specific
>than "Re: Contents of Tutor digest..."
>
>
>Today's Topics:
>
>   1. Re: Having a return when subprocess.Popen finishes (Nick Raptis)
>   2. Re: Having a return when subprocess.Popen finishes (Payal)
>   3. Re: Django Read (Huy Ton That)
>   4. Re: differences between mmap and StringIO (Christopher King)
>   5. Re: Tkinter mainloop() (Francesco Loffredo)
>
>
>----------------------------------------------------------------------
>
>Message: 1
>Date: Thu, 08 Jul 2010 16:33:02 +0300
>From: Nick Raptis <airscorp at otenet.gr>
>To: tutor at python.org
>Subject: Re: [Tutor] Having a return when subprocess.Popen finishes
>Message-ID: <4C35D38E.4090904 at otenet.gr>
>Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
>subprocess.Popen is a class, and as such it returns an object which can 
>do a lot of stuff besides just reading the output.
>
>What you want to do here is using it's communicate() method as such:
>
>output, errors = ping.communicate()
>
>
>Also, there is a quicker way, I think from version 2.7 forward: use  the 
>shortcut
>output = subprocess.check_output("your command here")
>
>Always check latest documentation for your python version too
>http://docs.python.org/library/subprocess.html
>
>Nick
>
>On 07/08/2010 04:04 PM, Paul VanGundy wrote:
>> Hi All,
>>
>> I'm trying to get data from subprocess.Popen. To be specific, I am
>> trying to read a ping echo and take the output and assign it to a
>> variable like below:
>>
>> ping = subprocess.Popen("ping -c 5 %s" % (server),
>> stdout=subprocess.PIPE, shell=True)
>>
>> However, when I run the command the output that gets assigned to my ping
>> variable is something along the lines of '<subprocess.Popen object at
>> 0x9524bec>' and am not returned to>>>  prompt. I know that is the proper
>> output but I need to be able to capture the ping replies and assign
>> those to a variable. I tried adding a \r and \n at the end of my cmd.
>> Any help would be greatly appreciated. I'm open to improvements,
>> different ways of doing it and corrections. :) If more info is needed
>> let me know. Thanks.
>>
>> /paul
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>    
>
>
>------------------------------
>
>Message: 2
>Date: Thu, 8 Jul 2010 06:39:51 -0700
>From: Payal <payal-python at scriptkitchen.com>
>To: tutor at python.org
>Subject: Re: [Tutor] Having a return when subprocess.Popen finishes
>Message-ID: <20100708133951.GA4572 at scriptkitchen.com>
>Content-Type: text/plain; charset=us-ascii
>
>On Thu, Jul 08, 2010 at 09:04:54AM -0400, Paul VanGundy wrote:
>> Hi All,
>> 
>> I'm trying to get data from subprocess.Popen. To be specific, I am
>> trying to read a ping echo and take the output and assign it to a
>> variable like below:
>> 
>> ping = subprocess.Popen("ping -c 5 %s" % (server),
>> stdout=subprocess.PIPE, shell=True)
>
>>>> import subprocess
>>>> server = 'localhost'
>>>> ping = subprocess.Popen("ping -c 5 %s" %
>>>> (server),stdout=subprocess.PIPE, shell=True)
>>>> ping.communicate()
>('PING localhost (127.0.0.1) 56(84) bytes of data.\n64 bytes from
>localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.044 ms\n64 bytes from
>localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.046 ms\n64 bytes from
>localhost (127.0.0.1): icmp_seq=3 ttl=64 time=0.052 ms\n64 bytes from
>localhost (127.0.0.1): icmp_seq=4 ttl=64 time=0.046 ms\n64 bytes from
>localhost (127.0.0.1): icmp_seq=5 ttl=64 time=0.049 ms\n\n--- localhost
>ping statistics ---\n5 packets transmitted, 5 received, 0% packet loss,
>time 3997ms\nrtt min/avg/max/mdev = 0.044/0.047/0.052/0.006 ms\n', None)
>>>>
>
>hth,
>With warm regards,
>-Payal
>-- 
>
>
>
>------------------------------
>
>Message: 3
>Date: Thu, 8 Jul 2010 10:19:38 -0400
>From: Huy Ton That <huyslogic at gmail.com>
>To: Jeff Johnson <jeff at dcsoftware.com>
>Cc: tutor at python.org
>Subject: Re: [Tutor] Django Read
>Message-ID:
>	<AANLkTik4qWUfiMJC3-gR4y4WX36PKHUIAyjbpT-lm7B9 at mail.gmail.com>
>Content-Type: text/plain; charset="iso-8859-1"
>
>I've went through the djangobook myself, and found it quite readable. This
>would be my recommendation as well.
>
>Be sure to read the sidebar comments; if you ever feel stuck, someone else
>may have addressed the question/answer for you!
>
>-Lee
>
>On Thu, Jul 8, 2010 at 9:31 AM, Jeff Johnson <jeff at dcsoftware.com> wrote:
>
>> On 07/08/2010 06:06 AM, Nick Raptis wrote:
>>
>>> There actually aren't that many books on django around yet which is a
>>> pity.
>>> You should definitely read "The django book":
>>> http://www.djangobook.com/en/2.0/
>>> either on the online version on that link, or it's printed counterpart
>>> (yes, it's really the same book):
>>> http://www.amazon.com/Definitive-Guide-Django-Development-Second/dp/143021936X/
>>>
>>> The printed one is a bit more updated (1.1) and pays off it's money
>>> because of it's great reference section :)
>>>
>>> Nick
>>>
>>> On 07/08/2010 03:48 PM, Dipo Elegbede wrote:
>>>
>>>> Hi all,
>>>>
>>>> I have done a little basic on python and have to start working on a
>>>> major django platform.
>>>> I'm starting new and would like recommendations on books I can read.
>>>>
>>>> Kindly help me out. I want to get my hands dirty as fast as I can so
>>>> that I can be part of the project.
>>>>
>>>> Thanks and Best regards,
>>>>
>>>>
>>>  I have six books on my bookshelf for Django.  There are others I don't
>> have.  Django 1.0 Template Development is my favorite.  Many of them walk
>> you through building apps step by step.  Do a search on Amazon.  That is
>> where I got most of them.
>>
>> --
>> Jeff
>>
>> -------------------
>>
>> Jeff Johnson
>> jeff at dcsoftware.com
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>-------------- next part --------------
>An HTML attachment was scrubbed...
>URL: <http://mail.python.org/pipermail/tutor/attachments/20100708/ebcdec1c/attachment-0001.html>
>
>------------------------------
>
>Message: 4
>Date: Thu, 8 Jul 2010 18:39:33 -0400
>From: Christopher King <g.nius.ck at gmail.com>
>To: Eduardo Vieira <eduardo.susan at gmail.com>
>Cc: Tutor Mailing List <tutor at python.org>
>Subject: Re: [Tutor] differences between mmap and StringIO
>Message-ID:
>	<AANLkTin1YIBQ5BIOoZu95NYLv_FGRcVuWRHWtHkPnZbf at mail.gmail.com>
>Content-Type: text/plain; charset="iso-8859-1"
>
>Well, I would just use the builting function open. I think Nick said in the
>beggining. Or, I would use the module I created. It's a file object, with
>the property file_txt. Unlike the other modules which you have to use read
>and write methods, I made a method which allows you to manulipulate like a
>string. I didn't even add a appending feature, but doing file.file_txt +=
>'bla', you can append. I can send it to you if you like.
>
>On Wed, Jul 7, 2010 at 6:52 PM, Eduardo Vieira <eduardo.susan at gmail.com>wrote:
>
>> Hello, I'm getting confused about the usage of those 2 modules. Which
>> should I use one to get/manipulate data from a text file?
>>
>> Regards,
>>
>> Eduardo
>> www.express-sign-supply.com
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>-------------- next part --------------
>An HTML attachment was scrubbed...
>URL: <http://mail.python.org/pipermail/tutor/attachments/20100708/45f9c016/attachment-0001.html>
>
>------------------------------
>
>Message: 5
>Date: Thu, 08 Jul 2010 20:40:36 +0200
>From: Francesco Loffredo <ilcomputertrasparente at gmail.com>
>To: tutor at python.org
>Subject: Re: [Tutor] Tkinter mainloop()
>Message-ID: <4C361BA4.4050002 at libero.it>
>Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
>
>
>Il 07/07/2010 9.11, Alan Gauld wrote:
>>
>> "Francesco Loffredo" <ilcomputertrasparente at gmail.com> wrote
>>
>>> ... What's the
>>> difference between the two methods?
>>
>> Its a little bit subtle but I believbe update() updates all widgets
>> whereas update_idle_tasks will only update those widgets that
>> have changed since the last update. In a complex GUI this can
>> be notably faster. Most of the books I've seen recommend not
>> using update() as it can cause race conditions but I have no experience
>> of that - because I use update_idle_tasks! :-)
>
>Ok, now I'm using update_idletasks() too (update_idle_tasks() doesn't 
>exist) and I like it. Thanks a lot!
>
>> ...
>
>>> where would you put the
>>> automatic move call, if not where I did? I need an automatic move be
>>> performed at the proper moment, when it's the computer player turn.
>>
>> Create the auto move in an event handler of its own and associate
>> with an event. Then raise that event when your players move is finished.
>> Tkinter will then call the automove for you, updating the screeen
>> automatically. In an event driven environment control is passed
>> around by means of events.
>I prefer not to make this project fully event driven, because while it's 
>fairly easy to translate a mouse click into the game coordinates of the 
>hex that's being clicked, I don't like translating a pair of integers to 
>some point (maybe the center) of an hexagon, creating an Event 
>structure, raising that Event and handling it, just to figure out...the 
>same couple of integers I started with. No, I prefer not to create fake 
>Events when there's none involved... at least in this little game. I'll 
>remember your advice for some serious project!
>>
>> How do you raise an event in Tkinter?
>> Use the event_generate() method.
>And this would have been my next question, thanks for mind-reading!
>>
>> Alternatively use the after() method with a short delay - say 10ms...
>That's what I actually did. It plays like a charm! THANK YOU!
>>
>> HTH,
>   SID!
>
>Francesco
>
>
>------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>End of Tutor Digest, Vol 77, Issue 25
>*************************************

From edwardlang at optonline.net  Fri Jul  9 13:22:08 2010
From: edwardlang at optonline.net (Edward Lang)
Date: Fri, 09 Jul 2010 07:22:08 -0400
Subject: [Tutor] Tutor Digest, Vol 77, Issue 25
Message-ID: <7qf6wyv1urev9495fcg02u9k.1278674528642@email.android.com>



tutor-request at python.org wrote:

>Send Tutor mailing list submissions to
>	tutor at python.org
>
>To subscribe or unsubscribe via the World Wide Web, visit
>	http://mail.python.org/mailman/listinfo/tutor
>or, via email, send a message with subject or body 'help' to
>	tutor-request at python.org
>
>You can reach the person managing the list at
>	tutor-owner at python.org
>
>When replying, please edit your Subject line so it is more specific
>than "Re: Contents of Tutor digest..."
>
>
>Today's Topics:
>
>   1. Re: Having a return when subprocess.Popen finishes (Nick Raptis)
>   2. Re: Having a return when subprocess.Popen finishes (Payal)
>   3. Re: Django Read (Huy Ton That)
>   4. Re: differences between mmap and StringIO (Christopher King)
>   5. Re: Tkinter mainloop() (Francesco Loffredo)
>
>
>----------------------------------------------------------------------
>
>Message: 1
>Date: Thu, 08 Jul 2010 16:33:02 +0300
>From: Nick Raptis <airscorp at otenet.gr>
>To: tutor at python.org
>Subject: Re: [Tutor] Having a return when subprocess.Popen finishes
>Message-ID: <4C35D38E.4090904 at otenet.gr>
>Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
>subprocess.Popen is a class, and as such it returns an object which can 
>do a lot of stuff besides just reading the output.
>
>What you want to do here is using it's communicate() method as such:
>
>output, errors = ping.communicate()
>
>
>Also, there is a quicker way, I think from version 2.7 forward: use  the 
>shortcut
>output = subprocess.check_output("your command here")
>
>Always check latest documentation for your python version too
>http://docs.python.org/library/subprocess.html
>
>Nick
>
>On 07/08/2010 04:04 PM, Paul VanGundy wrote:
>> Hi All,
>>
>> I'm trying to get data from subprocess.Popen. To be specific, I am
>> trying to read a ping echo and take the output and assign it to a
>> variable like below:
>>
>> ping = subprocess.Popen("ping -c 5 %s" % (server),
>> stdout=subprocess.PIPE, shell=True)
>>
>> However, when I run the command the output that gets assigned to my ping
>> variable is something along the lines of '<subprocess.Popen object at
>> 0x9524bec>' and am not returned to>>>  prompt. I know that is the proper
>> output but I need to be able to capture the ping replies and assign
>> those to a variable. I tried adding a \r and \n at the end of my cmd.
>> Any help would be greatly appreciated. I'm open to improvements,
>> different ways of doing it and corrections. :) If more info is needed
>> let me know. Thanks.
>>
>> /paul
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>    
>
>
>------------------------------
>
>Message: 2
>Date: Thu, 8 Jul 2010 06:39:51 -0700
>From: Payal <payal-python at scriptkitchen.com>
>To: tutor at python.org
>Subject: Re: [Tutor] Having a return when subprocess.Popen finishes
>Message-ID: <20100708133951.GA4572 at scriptkitchen.com>
>Content-Type: text/plain; charset=us-ascii
>
>On Thu, Jul 08, 2010 at 09:04:54AM -0400, Paul VanGundy wrote:
>> Hi All,
>> 
>> I'm trying to get data from subprocess.Popen. To be specific, I am
>> trying to read a ping echo and take the output and assign it to a
>> variable like below:
>> 
>> ping = subprocess.Popen("ping -c 5 %s" % (server),
>> stdout=subprocess.PIPE, shell=True)
>
>>>> import subprocess
>>>> server = 'localhost'
>>>> ping = subprocess.Popen("ping -c 5 %s" %
>>>> (server),stdout=subprocess.PIPE, shell=True)
>>>> ping.communicate()
>('PING localhost (127.0.0.1) 56(84) bytes of data.\n64 bytes from
>localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.044 ms\n64 bytes from
>localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.046 ms\n64 bytes from
>localhost (127.0.0.1): icmp_seq=3 ttl=64 time=0.052 ms\n64 bytes from
>localhost (127.0.0.1): icmp_seq=4 ttl=64 time=0.046 ms\n64 bytes from
>localhost (127.0.0.1): icmp_seq=5 ttl=64 time=0.049 ms\n\n--- localhost
>ping statistics ---\n5 packets transmitted, 5 received, 0% packet loss,
>time 3997ms\nrtt min/avg/max/mdev = 0.044/0.047/0.052/0.006 ms\n', None)
>>>>
>
>hth,
>With warm regards,
>-Payal
>-- 
>
>
>
>------------------------------
>
>Message: 3
>Date: Thu, 8 Jul 2010 10:19:38 -0400
>From: Huy Ton That <huyslogic at gmail.com>
>To: Jeff Johnson <jeff at dcsoftware.com>
>Cc: tutor at python.org
>Subject: Re: [Tutor] Django Read
>Message-ID:
>	<AANLkTik4qWUfiMJC3-gR4y4WX36PKHUIAyjbpT-lm7B9 at mail.gmail.com>
>Content-Type: text/plain; charset="iso-8859-1"
>
>I've went through the djangobook myself, and found it quite readable. This
>would be my recommendation as well.
>
>Be sure to read the sidebar comments; if you ever feel stuck, someone else
>may have addressed the question/answer for you!
>
>-Lee
>
>On Thu, Jul 8, 2010 at 9:31 AM, Jeff Johnson <jeff at dcsoftware.com> wrote:
>
>> On 07/08/2010 06:06 AM, Nick Raptis wrote:
>>
>>> There actually aren't that many books on django around yet which is a
>>> pity.
>>> You should definitely read "The django book":
>>> http://www.djangobook.com/en/2.0/
>>> either on the online version on that link, or it's printed counterpart
>>> (yes, it's really the same book):
>>> http://www.amazon.com/Definitive-Guide-Django-Development-Second/dp/143021936X/
>>>
>>> The printed one is a bit more updated (1.1) and pays off it's money
>>> because of it's great reference section :)
>>>
>>> Nick
>>>
>>> On 07/08/2010 03:48 PM, Dipo Elegbede wrote:
>>>
>>>> Hi all,
>>>>
>>>> I have done a little basic on python and have to start working on a
>>>> major django platform.
>>>> I'm starting new and would like recommendations on books I can read.
>>>>
>>>> Kindly help me out. I want to get my hands dirty as fast as I can so
>>>> that I can be part of the project.
>>>>
>>>> Thanks and Best regards,
>>>>
>>>>
>>>  I have six books on my bookshelf for Django.  There are others I don't
>> have.  Django 1.0 Template Development is my favorite.  Many of them walk
>> you through building apps step by step.  Do a search on Amazon.  That is
>> where I got most of them.
>>
>> --
>> Jeff
>>
>> -------------------
>>
>> Jeff Johnson
>> jeff at dcsoftware.com
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>-------------- next part --------------
>An HTML attachment was scrubbed...
>URL: <http://mail.python.org/pipermail/tutor/attachments/20100708/ebcdec1c/attachment-0001.html>
>
>------------------------------
>
>Message: 4
>Date: Thu, 8 Jul 2010 18:39:33 -0400
>From: Christopher King <g.nius.ck at gmail.com>
>To: Eduardo Vieira <eduardo.susan at gmail.com>
>Cc: Tutor Mailing List <tutor at python.org>
>Subject: Re: [Tutor] differences between mmap and StringIO
>Message-ID:
>	<AANLkTin1YIBQ5BIOoZu95NYLv_FGRcVuWRHWtHkPnZbf at mail.gmail.com>
>Content-Type: text/plain; charset="iso-8859-1"
>
>Well, I would just use the builting function open. I think Nick said in the
>beggining. Or, I would use the module I created. It's a file object, with
>the property file_txt. Unlike the other modules which you have to use read
>and write methods, I made a method which allows you to manulipulate like a
>string. I didn't even add a appending feature, but doing file.file_txt +=
>'bla', you can append. I can send it to you if you like.
>
>On Wed, Jul 7, 2010 at 6:52 PM, Eduardo Vieira <eduardo.susan at gmail.com>wrote:
>
>> Hello, I'm getting confused about the usage of those 2 modules. Which
>> should I use one to get/manipulate data from a text file?
>>
>> Regards,
>>
>> Eduardo
>> www.express-sign-supply.com
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>-------------- next part --------------
>An HTML attachment was scrubbed...
>URL: <http://mail.python.org/pipermail/tutor/attachments/20100708/45f9c016/attachment-0001.html>
>
>------------------------------
>
>Message: 5
>Date: Thu, 08 Jul 2010 20:40:36 +0200
>From: Francesco Loffredo <ilcomputertrasparente at gmail.com>
>To: tutor at python.org
>Subject: Re: [Tutor] Tkinter mainloop()
>Message-ID: <4C361BA4.4050002 at libero.it>
>Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
>
>
>Il 07/07/2010 9.11, Alan Gauld wrote:
>>
>> "Francesco Loffredo" <ilcomputertrasparente at gmail.com> wrote
>>
>>> ... What's the
>>> difference between the two methods?
>>
>> Its a little bit subtle but I believbe update() updates all widgets
>> whereas update_idle_tasks will only update those widgets that
>> have changed since the last update. In a complex GUI this can
>> be notably faster. Most of the books I've seen recommend not
>> using update() as it can cause race conditions but I have no experience
>> of that - because I use update_idle_tasks! :-)
>
>Ok, now I'm using update_idletasks() too (update_idle_tasks() doesn't 
>exist) and I like it. Thanks a lot!
>
>> ...
>
>>> where would you put the
>>> automatic move call, if not where I did? I need an automatic move be
>>> performed at the proper moment, when it's the computer player turn.
>>
>> Create the auto move in an event handler of its own and associate
>> with an event. Then raise that event when your players move is finished.
>> Tkinter will then call the automove for you, updating the screeen
>> automatically. In an event driven environment control is passed
>> around by means of events.
>I prefer not to make this project fully event driven, because while it's 
>fairly easy to translate a mouse click into the game coordinates of the 
>hex that's being clicked, I don't like translating a pair of integers to 
>some point (maybe the center) of an hexagon, creating an Event 
>structure, raising that Event and handling it, just to figure out...the 
>same couple of integers I started with. No, I prefer not to create fake 
>Events when there's none involved... at least in this little game. I'll 
>remember your advice for some serious project!
>>
>> How do you raise an event in Tkinter?
>> Use the event_generate() method.
>And this would have been my next question, thanks for mind-reading!
>>
>> Alternatively use the after() method with a short delay - say 10ms...
>That's what I actually did. It plays like a charm! THANK YOU!
>>
>> HTH,
>   SID!
>
>Francesco
>
>
>------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>End of Tutor Digest, Vol 77, Issue 25
>*************************************

From bgailer at gmail.com  Fri Jul  9 16:16:47 2010
From: bgailer at gmail.com (bob gailer)
Date: Fri, 09 Jul 2010 10:16:47 -0400
Subject: [Tutor] Tutor Digest, Vol 77, Issue 25
In-Reply-To: <s38uw3ob7m0202pkgaaja08u.1278674514648@email.android.com>
References: <s38uw3ob7m0202pkgaaja08u.1278674514648@email.android.com>
Message-ID: <4C372F4F.4000802@gmail.com>

We received 2 copies of the tutor digest from you.

If you intentionally sent it - why?

Please do not do that again. If you have a specific question or comment
- change the subject to something more meaningful
- delete everything from the digest that is not related to your question.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From hyperneato at gmail.com  Sat Jul 10 18:48:38 2010
From: hyperneato at gmail.com (Isaac)
Date: Sat, 10 Jul 2010 09:48:38 -0700
Subject: [Tutor] feedback on permutations script
Message-ID: <AANLkTimJmIib82kEChYSd4minJ9oEbjnbR7YbLH4Gdbl@mail.gmail.com>

This is my interpretation of an algorithm to generate all permutations
of items in a list. I would appreciate any feedback regarding advice
for improvements.

Thank you,

-Isaac

#!/usr/bin/python

def add_at_index(new_item, target_array, target_index):
    """
    new_item is a single list item.
    target_array is a list or iterable.
    target_index is a number.

    This function returns a new list that inserts new_item inside target_array
    at target_array's target_index. The new list will be 1 element longer
    than before.
    """

    new_list = target_array[:]

    new_list.insert(target_index, new_item)
    return new_list


def append_lists(working_list, list_of_lists):
    # appends every list in list_of_lists to working_list; returns working_list
    for _list in list_of_lists:
        working_list.append(_list)
    return working_list


def insert_each(orphan_item, target_array):
    """
    orphan_item is a single list item.
    target_array is a list or iterable.

    This function returns a list of lists that place orphan_item in
between and at
    the ends of each list element in target_array
    """

    new_array_length = len(target_array) + 1
    array_of_arrays = []

    for count in range(new_array_length):
        array_of_arrays.append(add_at_index(orphan_item, target_array, count))

    return array_of_arrays



def permute(original_list, list_of_lists):
    """
    accept a list of items, original_list, to insert one at a time
into list_of_lists
    using the function insert_each. Called for the first time,
    new_list is a list containing an empty list. Then call recursively using
    an updated list_of_lists, called new_list_of_lists below, and the remaining
    items in original list.
    """
    try:
        last_item = original_list.pop()
    except IndexError:
        # if the final iteration has been completed
        return list_of_lists

    if list_of_lists == [[]]: # it is the first iteration
        # call the next iteration recursively
        return permute(original_list, [[last_item]])
    else:
        # placeholder for new permutations
        new_list_of_lists = []
        for array in list_of_lists:
            permutation_set = insert_each(last_item, array)
            append_lists(new_list_of_lists, permutation_set)
    # call recursively
    return permute(original_list, new_list_of_lists)

From delegbede at dudupay.com  Sat Jul 10 19:05:37 2010
From: delegbede at dudupay.com (Dipo Elegbede)
Date: Sat, 10 Jul 2010 18:05:37 +0100
Subject: [Tutor] what is wrong with the syntax?
Message-ID: <AANLkTinpJbLJjY0Fxc9h6lEk7HZy88D9MMQkYQQoKQEZ@mail.gmail.com>

Hi all,

please tell me what is wrong with the syntax as written herein:

http://pastebin.com/BkLi0A4H

I am actually trying to let a user input something and have the input
returned in a reverse form and also see the lenght of the input.

please help.

-- 
Elegbede Muhammed Oladipupo
OCA
+2348077682428
+2347042171716
www.dudupay.com
Mobile Banking Solutions | Transaction Processing | Enterprise Application
Development
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100710/90e9e01a/attachment.html>

From steve at alchemy.com  Sat Jul 10 19:18:32 2010
From: steve at alchemy.com (Steve Willoughby)
Date: Sat, 10 Jul 2010 10:18:32 -0700
Subject: [Tutor] what is wrong with the syntax?
In-Reply-To: <AANLkTinpJbLJjY0Fxc9h6lEk7HZy88D9MMQkYQQoKQEZ@mail.gmail.com>
References: <AANLkTinpJbLJjY0Fxc9h6lEk7HZy88D9MMQkYQQoKQEZ@mail.gmail.com>
Message-ID: <4C38AB68.5010808@alchemy.com>

On 10-Jul-10 10:05, Dipo Elegbede wrote:
> Hi all,
> please tell me what is wrong with the syntax as written herein:
> http://pastebin.com/BkLi0A4H
> I am actually trying to let a user input something and have the input
> returned in a reverse form and also see the lenght of the input.
> please help.

Is this for Python 3.x or 2.x?  It makes a big difference in what 
input() means.  I'm guessing 2.x from the rest of the script, so what 
you probably want is raw_input, not input.... unless you really want 
them to type Python source there which is interpreted as a list of 
values or whatever.

I'm not sure what you want to accomplish with str() and list(), though. 
  Those create a string, and then a list, but you never assign the new 
string or list to anything.  Neither actually changes the "wording" 
variable.

Remember that the comma separating items in the print statement is a 
syntactic feature of the language.  You have them inside the strings 
you're printing.

>
> --
> Elegbede Muhammed Oladipupo
> OCA
> +2348077682428
> +2347042171716
> www.dudupay.com <http://www.dudupay.com>
> Mobile Banking Solutions | Transaction Processing | Enterprise
> Application Development
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From alan.gauld at btinternet.com  Sat Jul 10 19:47:52 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 10 Jul 2010 18:47:52 +0100
Subject: [Tutor] what is wrong with the syntax?
References: <AANLkTinpJbLJjY0Fxc9h6lEk7HZy88D9MMQkYQQoKQEZ@mail.gmail.com>
Message-ID: <i1abo8$kht$1@dough.gmane.org>


"Dipo Elegbede" <delegbede at dudupay.com> wrote

> please tell me what is wrong with the syntax as written herein:
>
> http://pastebin.com/BkLi0A4H

Please post full error reports as well as the code. It helps a lot!

You code has numerous errrs in it but the syntax errors are in
the print statements. You need to separate the arguments to
print with commas.

Also for the function to do anything you need to call it.

> I am actually trying to let a user input something and have the 
> input
> returned in a reverse form and also see the lenght of the input.

I also think your call to list and reversed is the wrong way round.
It should be:

reversed(list(wording))

I see Steve has already picked up most of the other mistakes.

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




From anand.shashwat at gmail.com  Sun Jul 11 00:37:32 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Sun, 11 Jul 2010 04:07:32 +0530
Subject: [Tutor] feedback on permutations script
In-Reply-To: <AANLkTimJmIib82kEChYSd4minJ9oEbjnbR7YbLH4Gdbl@mail.gmail.com>
References: <AANLkTimJmIib82kEChYSd4minJ9oEbjnbR7YbLH4Gdbl@mail.gmail.com>
Message-ID: <AANLkTimleMjShsHyQASxDRca_r43WO4CKDopn88u0VY6@mail.gmail.com>

On Sat, Jul 10, 2010 at 10:18 PM, Isaac <hyperneato at gmail.com> wrote:

> This is my interpretation of an algorithm to generate all permutations
> of items in a list. I would appreciate any feedback regarding advice
> for improvements.
>

Why not try itertools.permutation


>
> Thank you,
>
> -Isaac
>
> #!/usr/bin/python
>
> def add_at_index(new_item, target_array, target_index):
>    """
>    new_item is a single list item.
>    target_array is a list or iterable.
>    target_index is a number.
>
>    This function returns a new list that inserts new_item inside
> target_array
>    at target_array's target_index. The new list will be 1 element longer
>    than before.
>    """
>
>    new_list = target_array[:]
>
>    new_list.insert(target_index, new_item)
>    return new_list
>
>
> def append_lists(working_list, list_of_lists):
>    # appends every list in list_of_lists to working_list; returns
> working_list
>    for _list in list_of_lists:
>        working_list.append(_list)
>    return working_list
>
>
> def insert_each(orphan_item, target_array):
>    """
>    orphan_item is a single list item.
>    target_array is a list or iterable.
>
>    This function returns a list of lists that place orphan_item in
> between and at
>    the ends of each list element in target_array
>    """
>
>    new_array_length = len(target_array) + 1
>    array_of_arrays = []
>
>    for count in range(new_array_length):
>        array_of_arrays.append(add_at_index(orphan_item, target_array,
> count))
>
>    return array_of_arrays
>
>
>
> def permute(original_list, list_of_lists):
>    """
>    accept a list of items, original_list, to insert one at a time
> into list_of_lists
>    using the function insert_each. Called for the first time,
>    new_list is a list containing an empty list. Then call recursively using
>    an updated list_of_lists, called new_list_of_lists below, and the
> remaining
>    items in original list.
>    """
>    try:
>        last_item = original_list.pop()
>    except IndexError:
>        # if the final iteration has been completed
>        return list_of_lists
>
>    if list_of_lists == [[]]: # it is the first iteration
>        # call the next iteration recursively
>        return permute(original_list, [[last_item]])
>    else:
>        # placeholder for new permutations
>        new_list_of_lists = []
>        for array in list_of_lists:
>            permutation_set = insert_each(last_item, array)
>            append_lists(new_list_of_lists, permutation_set)
>    # call recursively
>    return permute(original_list, new_list_of_lists)
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100711/cfc9ad05/attachment.html>

From hyperneato at gmail.com  Sun Jul 11 01:10:14 2010
From: hyperneato at gmail.com (Isaac)
Date: Sat, 10 Jul 2010 16:10:14 -0700
Subject: [Tutor] feedback on permutations script
In-Reply-To: <AANLkTimleMjShsHyQASxDRca_r43WO4CKDopn88u0VY6@mail.gmail.com>
References: <AANLkTimJmIib82kEChYSd4minJ9oEbjnbR7YbLH4Gdbl@mail.gmail.com>
	<AANLkTimleMjShsHyQASxDRca_r43WO4CKDopn88u0VY6@mail.gmail.com>
Message-ID: <AANLkTiksWnxyd1OinByekyAM399HgZQGPmyEAaD1zIV4@mail.gmail.com>

Thanks, I will look at the source of itertools.permutations to learn
how it is done. I want to learn more about how to write algorithms
well. Looking at the source and asking questions as they come up is a
great idea.

On Sat, Jul 10, 2010 at 3:37 PM, Shashwat Anand
<anand.shashwat at gmail.com> wrote:
>
>
> On Sat, Jul 10, 2010 at 10:18 PM, Isaac <hyperneato at gmail.com> wrote:
>>
>> This is my interpretation of an algorithm to generate all permutations
>> of items in a list. I would appreciate any feedback regarding advice
>> for improvements.
>
> Why not try itertools.permutation
>
>>
>> Thank you,
>>
>> -Isaac
>>
>> #!/usr/bin/python
>>
>> def add_at_index(new_item, target_array, target_index):
>> ? ?"""
>> ? ?new_item is a single list item.
>> ? ?target_array is a list or iterable.
>> ? ?target_index is a number.
>>
>> ? ?This function returns a new list that inserts new_item inside
>> target_array
>> ? ?at target_array's target_index. The new list will be 1 element longer
>> ? ?than before.
>> ? ?"""
>>
>> ? ?new_list = target_array[:]
>>
>> ? ?new_list.insert(target_index, new_item)
>> ? ?return new_list
>>
>>
>> def append_lists(working_list, list_of_lists):
>> ? ?# appends every list in list_of_lists to working_list; returns
>> working_list
>> ? ?for _list in list_of_lists:
>> ? ? ? ?working_list.append(_list)
>> ? ?return working_list
>>
>>
>> def insert_each(orphan_item, target_array):
>> ? ?"""
>> ? ?orphan_item is a single list item.
>> ? ?target_array is a list or iterable.
>>
>> ? ?This function returns a list of lists that place orphan_item in
>> between and at
>> ? ?the ends of each list element in target_array
>> ? ?"""
>>
>> ? ?new_array_length = len(target_array) + 1
>> ? ?array_of_arrays = []
>>
>> ? ?for count in range(new_array_length):
>> ? ? ? ?array_of_arrays.append(add_at_index(orphan_item, target_array,
>> count))
>>
>> ? ?return array_of_arrays
>>
>>
>>
>> def permute(original_list, list_of_lists):
>> ? ?"""
>> ? ?accept a list of items, original_list, to insert one at a time
>> into list_of_lists
>> ? ?using the function insert_each. Called for the first time,
>> ? ?new_list is a list containing an empty list. Then call recursively
>> using
>> ? ?an updated list_of_lists, called new_list_of_lists below, and the
>> remaining
>> ? ?items in original list.
>> ? ?"""
>> ? ?try:
>> ? ? ? ?last_item = original_list.pop()
>> ? ?except IndexError:
>> ? ? ? ?# if the final iteration has been completed
>> ? ? ? ?return list_of_lists
>>
>> ? ?if list_of_lists == [[]]: # it is the first iteration
>> ? ? ? ?# call the next iteration recursively
>> ? ? ? ?return permute(original_list, [[last_item]])
>> ? ?else:
>> ? ? ? ?# placeholder for new permutations
>> ? ? ? ?new_list_of_lists = []
>> ? ? ? ?for array in list_of_lists:
>> ? ? ? ? ? ?permutation_set = insert_each(last_item, array)
>> ? ? ? ? ? ?append_lists(new_list_of_lists, permutation_set)
>> ? ?# call recursively
>> ? ?return permute(original_list, new_list_of_lists)
>

From steve at pearwood.info  Sun Jul 11 05:29:58 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 11 Jul 2010 13:29:58 +1000
Subject: [Tutor] feedback on permutations script
In-Reply-To: <AANLkTimJmIib82kEChYSd4minJ9oEbjnbR7YbLH4Gdbl@mail.gmail.com>
References: <AANLkTimJmIib82kEChYSd4minJ9oEbjnbR7YbLH4Gdbl@mail.gmail.com>
Message-ID: <201007111330.10149.steve@pearwood.info>

On Sun, 11 Jul 2010 02:48:38 am Isaac wrote:
> This is my interpretation of an algorithm to generate all
> permutations of items in a list. I would appreciate any feedback
> regarding advice for improvements.

Some of this is going to just be personal style, some of this is going 
to be slightly stronger semi-official recommended style (PEP 8 if you 
want to google further), and right at the end some hints regarding the 
algorith.


> #!/usr/bin/python

If you're on Linux, it is generally recommended to use a shebang line 
of "#!/usr/bin/env python". Python can be installed in different 
places, while /usr/bin is the standard location for env. Of course, 
this isn't entirely portable either...


> def add_at_index(new_item, target_array, target_index):
>     """
>     new_item is a single list item.
>     target_array is a list or iterable.
>     target_index is a number.
>
>     This function returns a new list that inserts new_item inside
> target_array at target_array's target_index. The new list will be 1
> element longer than before.
>     """
>
>     new_list = target_array[:]
>
>     new_list.insert(target_index, new_item)
>     return new_list

This has misleading function and argument names: it's called 
add_at_index and takes an argument called target_array, but:

(1) target_array is not expected to be an array, but a list. People 
forget that Python *does* have a standard array type. Just import array 
to be reminded :)

(2) target_array is documented as being any iterable, but that's simply 
not correct. Try passing a tuple, string or iterator and watch it 
explode.

(3) The function and argument names imply that it *adds* to a *target*, 
but that's not what it does. It makes a copy. Unfortunately Python 
doesn't have a common convention for indicating functions that make a 
copy.

(4) target_index is said to be a number. Can you pass floats? Fractions? 
Decimals? Complex numbers?

(5) And the function is awfully verbose for such a tiny little thing.


I'm not very happy with the function name, but can't think of anything 
better that's not excessively long, so I'll keep the name. Here is how 
I would re-write the code:

def add_at_index(item, target, where):
    """Return a copy of target as a list and insert item at index where.

    item: any object
    target: any finite iterable
    where: an integer index
    """
    new_list = list(target)
    new_list.insert(where, item)
    return new_list


> def append_lists(working_list, list_of_lists):
>     # appends every list in list_of_lists to working_list; returns
> working_list 
>     for _list in list_of_lists: 
>         working_list.append(_list)
>     return working_list

You like those verbose variable names, don't you? :)

You have a comment, but no doc-string. Is that deliberate?

You have named a local variable "_list". This isn't *wrong* exactly, but 
it's very unusual. The standard convention in Python is that names 
starting with a single underscore are "private" names, but local 
variables inside a function are always private! Nothing outside of the 
function can get access to or see that variable, so marking it private 
is unnecessary.

If your only reason for using the underscore is to distinguish the 
variable from the built-in "list", then consider these alternatives:

* since this variable is just a generic name, you can use any 
  old generic name: L, mylist, alist, seq, ...

* where you absolutely have to use the word "list", the usual 
  Python convention to avoid shadowing the built-in is to 
  append the underscore to the end of the name: list_

* in a function this small, where you don't use the built-in
  list for anything, feel free to shadow the built-in. It won't
  hurt, although some people will hate it, and code checkers like
  PyLint or PyChecker may complain.


According to the comment and the name, list_of_lists must contain only 
lists. But why? There doesn't seem to be anything in the code that 
*requires* the items to be lists. This seems to be more of a 
multi-append than an append-lists function. So re-writing it:

def multi_append(target, items):
    """Return target list with each item of items appended.

    target: a list
    items: any sequence or iterable
    """
    for item in items:
        target.append(item)
    return target

But this function is entirely unnecessary, because that's exactly what 
the "extend" method does:

target.extend(items)


> def insert_each(orphan_item, target_array):
>     """
>     orphan_item is a single list item.
>     target_array is a list or iterable.
>
>     This function returns a list of lists that place orphan_item in
> between and at
>     the ends of each list element in target_array
>     """
>
>     new_array_length = len(target_array) + 1
>     array_of_arrays = []
>
>     for count in range(new_array_length):
>         array_of_arrays.append(add_at_index(orphan_item,
> target_array, count))
>
>     return array_of_arrays


The description of this function is complicated enough that it needs an 
example in the doc-string. Here's my version:


def insert_each(item, target):
    """Return a list of lists generated from target list by 
    inserting item into each position of the copy:

    >>> insert_each(0, [1, 2, 3])
    [[0, 1, 2, 3], [1, 0, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0]]

    item: any object
    target: any finite sequence or iterable.
    """
    result = []
    for i in range(len(target) + 1):
        new_list = add_at_index(item, target, i)
        result.append(new_list)
    return result



> def permute(original_list, list_of_lists):
>     """
>     accept a list of items, original_list, to insert one at a time
> into list_of_lists
>     using the function insert_each. Called for the first time, 
>     new_list is a list containing an empty list. Then call
> recursively using an updated list_of_lists, called new_list_of_lists
> below, and the remaining items in original list.
>     """

This tells *how* the function works, but not *why*, or *what* it is 
supposed to do. It says to set new_list to [[]] but there is no 
argument new_list, so what is the user supposed to do with it?

Similarly, your variable names tend to describe what they are made of, 
rather than what they represent. "list_of_lists" isn't just some 
arbitrary list containing other lists. It is a list of permutations. 
The fact that each permutation is a list is unimportant.

If the user must call a function with a particular argument, then don't 
make that a requirement. Just have the function create it itself.

There's no need to have the comments "call recursively". Presumably the 
reader can actually read. If you're reading a function called "permute" 
and see a call to permute(), then it's pretty safe to bet that it's a 
recursive call. That's not quite so bad as the archetypal Bad Comment:

    x = x+1  # add one to x

    Wow, thanks Captain Obvious, what would we do without you?
    *rolls eyes*

but it is approaching it. The only time it does need a comment is if, 
somehow, it ISN'T a recursive call.

So, re-writing using the updated functions above and (IMO) more sensible 
variable names, but leaving the basic algorithm alone:

def permute(seq, _permutations=None):
    """Return a list of all the permutations of seq.

    seq: a finite sequence or iterable.
    _permutations: private argument, do not supply this.

    >>> permute([1, 2, 3])
    [[1, 2, 3], [2, 1, 3], [2, 3, 1], ... [3, 2, 1]]
    """
    if _permutations is None:
        _permutations = [[]]
    if not isinstance(seq, list):
        seq = list(seq)
    try:
        item = seq.pop()
    except IndexError:
        # The final iteration has been completed, so we're done.
        return _permutations
    if _permutations == [[]]:
        _permutations = [[item]]
    else:
        temp = []
        for perm in _permutations[:]:
            perm = insert_each(item, perm)
            temp.extend(perm)
        _permutations = temp
    return permute(seq, _permutations)


A couple of comments:

* This is going to be inefficient even for quite small sizes 
  of the input list. It seems to me that you're doing a lot 
  of unnecessary copying of lists and inserting. But don't 
  take that as gospel, I'd need to think about it a bit more
  to be sure of that.

* However the basic approach -- to generate all the 
  permutations at once -- truly is very inefficient. The 
  number of permutations grows exponentially fast, and so do 
  the time and memory requirements. A better approach is to 
  generate the permutations lazily, one at a time: see Python 
  generators and the yield statement.

* Recursion in Python isn't as efficient as some other 
  languages, so this will be unnecessarily slow compared to
  a version using iteration. For small lists you won't notice
  the difference; for large lists you'll run out of memory 
  first; but for intermediate lists you could see some gains
  by re-writing using a loop.




-- 
Steven D'Aprano

From dotti at socialnerds.org  Sun Jul 11 15:59:59 2010
From: dotti at socialnerds.org (Dominik Danter)
Date: Sun, 11 Jul 2010 15:59:59 +0200
Subject: [Tutor] Function returns 'None'
Message-ID: <4C39CE5F.6020309@socialnerds.org>

Hello

As en exercise I wrote the following function:


def recursfac(x,carryover=1):
     print 'x:',x,'carryover:', carryover
     if x > 1:
         carryover *= x
         recursfac(x-1, carryover)
     else:
         return carryover

print recursfac(3)

Very much to my surprise I get the following output:

x: 3 carryover: 1
x: 2 carryover: 3
x: 1 carryover: 6
None

Where did I go wrong?

Kind regards
Dominik Danter

From adam.jtm30 at gmail.com  Sun Jul 11 16:46:40 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Sun, 11 Jul 2010 15:46:40 +0100
Subject: [Tutor] Function returns 'None'
In-Reply-To: <4C39CE5F.6020309@socialnerds.org>
References: <4C39CE5F.6020309@socialnerds.org>
Message-ID: <4C39D950.1020101@gmail.com>

On 11/07/10 14:59, Dominik Danter wrote:
> Hello
>
> As en exercise I wrote the following function:
>
>
> def recursfac(x,carryover=1):
>     print 'x:',x,'carryover:', carryover
>     if x > 1:
>         carryover *= x
>         recursfac(x-1, carryover)
>     else:
>         return carryover
>
> print recursfac(3)
>
> Very much to my surprise I get the following output:
>
> x: 3 carryover: 1
> x: 2 carryover: 3
> x: 1 carryover: 6
> None
>
> Where did I go wrong?
>
> Kind regards
> Dominik Danter

I made a diagram to try to explain

recursfac(3)
     recursfac(2, 3) <----|
         recursfac(1, 6)  _|

As you can see recursfac(1,6) returns it's value (carryover) to 
recursfac(2, 3) which ignores it and completes it's execution ie 
returning None to your original call which then prints out that return 
value.
I hope that's clear.

Adam.

From alan.gauld at btinternet.com  Sun Jul 11 17:09:02 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 11 Jul 2010 16:09:02 +0100
Subject: [Tutor] Function returns 'None'
References: <4C39CE5F.6020309@socialnerds.org>
Message-ID: <i1cmqf$bu6$1@dough.gmane.org>


"Dominik Danter" <dotti at socialnerds.org> wrote

> def recursfac(x,carryover=1):
>     print 'x:',x,'carryover:', carryover
>     if x > 1:
>         carryover *= x
>         recursfac(x-1, carryover)

No return value here so when the reursed function returns carryover
we have nowhere to go in the calling function so we return None.

>     else:
>         return carryover

This returns a value to the calling function, but in 
the recursive case that returned vaklue uis thrown away 
as the comment above shows.

you need to add a return statement where you call recursively.

HTH,

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



From airscorp at otenet.gr  Sun Jul 11 17:28:03 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Sun, 11 Jul 2010 18:28:03 +0300
Subject: [Tutor] Function returns 'None'
In-Reply-To: <4C39CE5F.6020309@socialnerds.org>
References: <4C39CE5F.6020309@socialnerds.org>
Message-ID: <4C39E303.3070607@otenet.gr>

On 07/11/2010 04:59 PM, Dominik Danter wrote:
> Hello
>
> As en exercise I wrote the following function:
>
>
> def recursfac(x,carryover=1):
>     print 'x:',x,'carryover:', carryover
>     if x > 1:
>         carryover *= x
>         recursfac(x-1, carryover)
>     else:
>         return carryover
>
> print recursfac(3)
>
> Very much to my surprise I get the following output:
>
> x: 3 carryover: 1
> x: 2 carryover: 3
> x: 1 carryover: 6
> None
>
> Where did I go wrong?
>
Your problem is that you expect the "return" to exit the recursion 
altogether. Instead, carryover is passed to the previous level of the 
recursion, which has nothing more to execute and returns None.

So the first step to fix this would be to make sure that your function 
returns carryover no matter what:

def recursfac(x,carryover=1):
     print 'x:',x,'carryover:', carryover
     if x > 1:
         carryover *= x
         recursfac(x-1, carryover)
         return carryover
     else:
         return carryover

Or simply (to remove the code duplication):

def recursfac(x,carryover=1):
     print 'x:',x,'carryover:', carryover
     if x > 1:
         carryover *= x
         recursfac(x-1, carryover)
     return carryover

Now there's still one more problem. The output is this:

x: 3 carryover: 1
x: 2 carryover: 3
x: 1 carryover: 6
3

Why is it returning 3 istead of 6?

Well, the function didn't catch the returned carryover value on the way 
up, so it's just returns what it knows: the value of carryover that it 
self has computed.
Instead, you have to do this:

def recursfac(x,carryover=1):
     print 'x:',x,'carryover:', carryover
     if x > 1:
         carryover *= x
         carryover = recursfac(x-1, carryover)
     return carryover

And this returns
x: 3 carryover: 1
x: 2 carryover: 3
x: 1 carryover: 6
6

Done!

What you should learn from this is that, when doing recursion, figuring 
out what your function should do on the way up is as crucial as what you 
want it to do on the way down.

Nick



From airscorp at otenet.gr  Sun Jul 11 17:43:16 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Sun, 11 Jul 2010 18:43:16 +0300
Subject: [Tutor] Function returns 'None'
In-Reply-To: <4C39E303.3070607@otenet.gr>
References: <4C39CE5F.6020309@socialnerds.org> <4C39E303.3070607@otenet.gr>
Message-ID: <4C39E694.9010206@otenet.gr>

On 07/11/2010 06:28 PM, Nick Raptis wrote:
>
> def recursfac(x,carryover=1):
>     print 'x:',x,'carryover:', carryover
>     if x > 1:
>         carryover *= x
>         carryover = recursfac(x-1, carryover)
>     return carryover
>
> And this returns
> x: 3 carryover: 1
> x: 2 carryover: 3
> x: 1 carryover: 6
> 6
>
> Done!
>

Also, I realized that my final code may be tough to decipher now.. A 
nicer way to write it would be (the functionality is still exactly the 
same):

def recursfac(x,carryover=1):
     print 'x:',x,'carryover:', carryover
     if x > 1:
         carryover *= x
         result = recursfac(x-1, carryover)
     else:
         # done with recursion, start our way up
         result = carryover
     return result



From rabidpoobear at gmail.com  Sun Jul 11 17:50:06 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 11 Jul 2010 10:50:06 -0500
Subject: [Tutor] Function returns 'None'
In-Reply-To: <4C39E694.9010206@otenet.gr>
References: <4C39CE5F.6020309@socialnerds.org> <4C39E303.3070607@otenet.gr>
	<4C39E694.9010206@otenet.gr>
Message-ID: <EFB3D300-F59D-4CAB-9315-E9E7450EA421@gmail.com>

I think the new version is harder to understand.

Sent from my iPhone

On Jul 11, 2010, at 10:43 AM, Nick Raptis <airscorp at otenet.gr> wrote:

> On 07/11/2010 06:28 PM, Nick Raptis wrote:
>> 
>> def recursfac(x,carryover=1):
>>    print 'x:',x,'carryover:', carryover
>>    if x > 1:
>>        carryover *= x
>>        carryover = recursfac(x-1, carryover)
>>    return carryover
>> 
>> And this returns
>> x: 3 carryover: 1
>> x: 2 carryover: 3
>> x: 1 carryover: 6
>> 6
>> 
>> Done!
>> 
> 
> Also, I realized that my final code may be tough to decipher now.. A nicer way to write it would be (the functionality is still exactly the same):
> 
> def recursfac(x,carryover=1):
>    print 'x:',x,'carryover:', carryover
>    if x > 1:
>        carryover *= x
>        result = recursfac(x-1, carryover)
>    else:
>        # done with recursion, start our way up
>        result = carryover
>    return result
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From airscorp at otenet.gr  Sun Jul 11 18:14:20 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Sun, 11 Jul 2010 19:14:20 +0300
Subject: [Tutor] Function returns 'None'
In-Reply-To: <EFB3D300-F59D-4CAB-9315-E9E7450EA421@gmail.com>
References: <4C39CE5F.6020309@socialnerds.org> <4C39E303.3070607@otenet.gr>
	<4C39E694.9010206@otenet.gr>
	<EFB3D300-F59D-4CAB-9315-E9E7450EA421@gmail.com>
Message-ID: <4C39EDDC.8090304@otenet.gr>

On 07/11/2010 06:50 PM, Luke Paireepinart wrote:
> I think the new version is harder to understand.
>
> Sent from my iPhone
>
> On Jul 11, 2010, at 10:43 AM, Nick Raptis<airscorp at otenet.gr>  wrote:
>
Aww! A critic! You humble me (really, I'm not being sarcastic here, I 
welcome it gladly)

I won't argue about it, though. If you prefer it, the last version is 
still there :)

My reasoning is that, with the new variable name ('result') in place, 
now it is evident (to me at least) that 'passover' is passed on the way 
down, while 'result' is passed on the way up. Harder it not, it seems 
more """"""clean""""""

Also, another preference of mine, would you be kind enough to answer to 
the list and cc the original poster if you can? Doing it the other way 
around breaks my (quite stupid I admit) filters, and perhaps others' too.

Thanks for the feedback.
Nick

From rabidpoobear at gmail.com  Sun Jul 11 18:24:56 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 11 Jul 2010 11:24:56 -0500
Subject: [Tutor] Function returns 'None'
In-Reply-To: <4C39EDDC.8090304@otenet.gr>
References: <4C39CE5F.6020309@socialnerds.org> <4C39E303.3070607@otenet.gr>
	<4C39E694.9010206@otenet.gr>
	<EFB3D300-F59D-4CAB-9315-E9E7450EA421@gmail.com>
	<4C39EDDC.8090304@otenet.gr>
Message-ID: <3A8F05B4-9955-4D89-B3C5-A8A32CD76618@gmail.com>

On Jul 11, 2010, at 11:14 AM, Nick Raptis <airscorp at otenet.gr> wrote:

>> 
>> 
>> 
> 
> Also, another preference of mine, would you be kind enough to answer to the list and cc the original poster if you can? Doing it the other way around breaks my (quite stupid I admit) filters, and perhaps others' too.
That's the default email setup for the iPhone. I agree it's silly but it seems quite difficult to modify the fields. I see your point about the variable names but if it's at least fairly obvious what you're intending to do it seems like a bit of a waste to have an extra variable and else block. But you know, potato potato. It's negligible from a performance standpoint, it's really just a question of readability. Do what makes you ( and the people who will read your code) happy.
-luke

From jf_byrnes at comcast.net  Sun Jul 11 19:42:28 2010
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Sun, 11 Jul 2010 12:42:28 -0500
Subject: [Tutor] Path?
Message-ID: <4C3A0284.6090901@comcast.net>

I am running Ubuntu.  I downloaded the source code examples for a book I 
purchased.  Some of the examples load image files located in the same 
directory as the program.  If I go to the current directory in the 
terminal the program can use the image files.  However, if I use a 
launcher or the filemanager it pops up an error dialog saying the file 
does not exist even though it is in the same directory.

The program simply uses the files name.  Is there a way without editing 
the source and inserting the full path to run the program from a 
launcher or the filemanager and allow it to see files in the current 
directory?

Thanks,  Jim

From hyperneato at gmail.com  Sun Jul 11 19:54:56 2010
From: hyperneato at gmail.com (Isaac)
Date: Sun, 11 Jul 2010 10:54:56 -0700
Subject: [Tutor] feedback on permutations script
Message-ID: <AANLkTil5jTnj4ZaAU44alzDy824iObdvBA26OsJ3XwIM@mail.gmail.com>

> On Sun, 11 Jul 2010 02:48:38 am Isaac wrote:
> >* This is my interpretation of an algorithm to generate all
*> >* permutations of items in a list. I would appreciate any feedback
*> >* regarding advice for improvements.
**> Steven D'Aprano* wrote:
    *Sun Jul 11 05:29:58 CEST 2010*
> Some of this is going to just be personal style, some of this is going
> to be slightly stronger semi-official recommended style (PEP 8 if you
> want to google further), and right at the end some hints regarding the
> algorithm.

Thank you for your vaulable insight and time. I'll make some changes.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100711/b5647e42/attachment.html>

From adam.jtm30 at gmail.com  Sun Jul 11 20:12:48 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Sun, 11 Jul 2010 19:12:48 +0100
Subject: [Tutor] Path?
In-Reply-To: <4C3A0284.6090901@comcast.net>
References: <4C3A0284.6090901@comcast.net>
Message-ID: <4C3A09A0.70708@gmail.com>

On 11/07/10 18:42, Jim Byrnes wrote:
> I am running Ubuntu.  I downloaded the source code examples for a book 
> I purchased.  Some of the examples load image files located in the 
> same directory as the program.  If I go to the current directory in 
> the terminal the program can use the image files.  However, if I use a 
> launcher or the filemanager it pops up an error dialog saying the file 
> does not exist even though it is in the same directory.
>
> The program simply uses the files name.  Is there a way without 
> editing the source and inserting the full path to run the program from 
> a launcher or the filemanager and allow it to see files in the current 
> directory?
>
> Thanks,  Jim
Maybe create a bash script to call the python code something like:

#!/bin/bash

cd /directory/the/scripts/are/in
python script_name

HTH,
Adam.

PS if you want to use the same script for any python script you could 
change the last line to:

python $1

and call the bash script with the python script as the first argument

From bala.biophysics at gmail.com  Sun Jul 11 23:41:14 2010
From: bala.biophysics at gmail.com (Bala subramanian)
Date: Sun, 11 Jul 2010 23:41:14 +0200
Subject: [Tutor] extract a submatrix
Message-ID: <AANLkTimICjdxxds7Uuv3j5x9G8WwLESwra-EDw8OCU32@mail.gmail.com>

Friends,
Excuse me if this question is not appropriate for this forum. I have a
matrix of size 550,550. I want to extract only part of this matrix say first
330 elements, i dnt need the last 220 elements in the matrix. is there any
function in numpy that can do this kind of extraction. I am quite new to
numpy. How can do the same ?

Thank you,
Bala
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100711/bfafd8b8/attachment.html>

From steve at pearwood.info  Mon Jul 12 01:32:06 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 12 Jul 2010 09:32:06 +1000
Subject: [Tutor] Path?
In-Reply-To: <4C3A0284.6090901@comcast.net>
References: <4C3A0284.6090901@comcast.net>
Message-ID: <201007120932.06800.steve@pearwood.info>

On Mon, 12 Jul 2010 03:42:28 am Jim Byrnes wrote:
> I am running Ubuntu.  I downloaded the source code examples for a
> book I purchased.  Some of the examples load image files located in
> the same directory as the program.  If I go to the current directory
> in the terminal the program can use the image files.  However, if I
> use a launcher or the filemanager it pops up an error dialog saying
> the file does not exist even though it is in the same directory.
>
> The program simply uses the files name.  Is there a way without
> editing the source and inserting the full path to run the program
> from a launcher or the filemanager and allow it to see files in the
> current directory?

What file manager are you using? Nautilus? Konqueror? Something else?

What do you mean, "use a launcher"? Use a launcher to do what? What sort 
of launcher?

What pops up an error dialog? The launcher?

Which file does it claim doesn't exist? Python? The Python script? The 
image file? What is the exact error message it gives?

There's probably a way to tell the launcher which working directory to 
use, but of course that depends on the answers to the above questions.



-- 
Steven D'Aprano

From eike.welk at gmx.net  Mon Jul 12 12:03:22 2010
From: eike.welk at gmx.net (Eike Welk)
Date: Mon, 12 Jul 2010 12:03:22 +0200
Subject: [Tutor] extract a submatrix
In-Reply-To: <AANLkTimICjdxxds7Uuv3j5x9G8WwLESwra-EDw8OCU32@mail.gmail.com>
References: <AANLkTimICjdxxds7Uuv3j5x9G8WwLESwra-EDw8OCU32@mail.gmail.com>
Message-ID: <201007121203.22922.eike.welk@gmx.net>

Hello Bala!

On Sunday July 11 2010 23:41:14 Bala subramanian wrote:
> I have a
> matrix of size 550,550. I want to extract only part of this matrix say
>  first 330 elements, i dnt need the last 220 elements in the matrix. is
>  there any function in numpy that can do this kind of extraction.

I demonstrate it with a integer matrix of dimension (5, 10):

In [3]: a = array(range(50)).reshape(5,10)

In [4]: a
Out[4]:
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])

In [5]: a[:, 0:7]
Out[5]:
array([[ 0,  1,  2,  3,  4,  5,  6],
       [10, 11, 12, 13, 14, 15, 16],
       [20, 21, 22, 23, 24, 25, 26],
       [30, 31, 32, 33, 34, 35, 36],
       [40, 41, 42, 43, 44, 45, 46]])

In [6]: a[:, 7:]
Out[6]:
array([[ 7,  8,  9],
       [17, 18, 19],
       [27, 28, 29],
       [37, 38, 39],
       [47, 48, 49]])


The colons ":" denote slices. In a 2D array you can have slices in two 
dimensions. in the first dimension (downwards) I always select all elements. 
A good explanation of slices is here:
http://tiny.cc/ohl2g
http://stackoverflow.com/questions/509211/good-primer-for-python-slice-
notation

A nice list of Numpy's many functions and methods is here: (This is the Numpy 
page I use most often.)
http://tiny.cc/qzwoq
http://www.scipy.org/Numpy_Example_List_With_Doc#head-11717acafb821da646a8db6997e59b820ac8761a

The funny prompt is from IPython (ipython --pylab), a program that enhances 
Python's interactive mode, and keeps Matplotlib graphs alive.


Eike.

From davea at ieee.org  Mon Jul 12 13:17:13 2010
From: davea at ieee.org (Dave Angel)
Date: Mon, 12 Jul 2010 07:17:13 -0400
Subject: [Tutor] extract a submatrix
In-Reply-To: <AANLkTimICjdxxds7Uuv3j5x9G8WwLESwra-EDw8OCU32@mail.gmail.com>
References: <AANLkTimICjdxxds7Uuv3j5x9G8WwLESwra-EDw8OCU32@mail.gmail.com>
Message-ID: <4C3AF9B9.2050101@ieee.org>



Bala subramanian wrote:
> Friends,
> Excuse me if this question is not appropriate for this forum. I have a
> matrix of size 550,550. I want to extract only part of this matrix say first
> 330 elements, i dnt need the last 220 elements in the matrix. is there any
> function in numpy that can do this kind of extraction. I am quite new to
> numpy. How can do the same ?
>
> Thank you,
> Bala
>
>   
I don't know numpy, and it probably would be better to use that forum.  
But there are several people here who do, and one of them will probably 
help.

However, I would point out that if you fetch the first 220 elements of a 
550x550 matrix, you'll have 302170 elements left.

DaveA


From bala.biophysics at gmail.com  Mon Jul 12 15:38:36 2010
From: bala.biophysics at gmail.com (Bala subramanian)
Date: Mon, 12 Jul 2010 15:38:36 +0200
Subject: [Tutor] extract a submatrix
In-Reply-To: <4C3AF9B9.2050101@ieee.org>
References: <AANLkTimICjdxxds7Uuv3j5x9G8WwLESwra-EDw8OCU32@mail.gmail.com>
	<4C3AF9B9.2050101@ieee.org>
Message-ID: <AANLkTikCw1ekYksYvGUjxJT6TgoCNvIZjFtH3r_3owlB@mail.gmail.com>

Dear Eike,
Thank you so much, the simple slicing operation solved my problem. Thank you
for the links, i am just going through the same.

Dave
I wanted was to extract a matrix of dimension 330,330 from a matrix of
dimension 550,550. Sorry if my previous post was not clear. I am able to do
it by slicing as suggested by Eike.

Thank you,
Bala

On Mon, Jul 12, 2010 at 1:17 PM, Dave Angel <davea at ieee.org> wrote:

>
>
> Bala subramanian wrote:
>
>> Friends,
>> Excuse me if this question is not appropriate for this forum. I have a
>> matrix of size 550,550. I want to extract only part of this matrix say
>> first
>> 330 elements, i dnt need the last 220 elements in the matrix. is there any
>> function in numpy that can do this kind of extraction. I am quite new to
>> numpy. How can do the same ?
>>
>> Thank you,
>> Bala
>>
>>
>>
> I don't know numpy, and it probably would be better to use that forum.  But
> there are several people here who do, and one of them will probably help.
>
> However, I would point out that if you fetch the first 220 elements of a
> 550x550 matrix, you'll have 302170 elements left.
>
> DaveA
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100712/7c47092c/attachment.html>

From huyslogic at gmail.com  Mon Jul 12 16:49:04 2010
From: huyslogic at gmail.com (Huy Ton That)
Date: Mon, 12 Jul 2010 10:49:04 -0400
Subject: [Tutor] Python Documentation Clarification
Message-ID: <AANLkTikL5D727s3kCyG8W4LHnV-Gpd3BLEBZXMKJokRk@mail.gmail.com>

This is going to sound silly, but I realized there are some areas within the
documentation that do not make absolute sense to me.

e.g.

compile(source, filename, mode[, flags[, dont_inherit]])

I see within this built in function, the first argument can be what they
define as source, the second argument as the filename and the third as the
mode.

But what confuses me is sometimes I see a bracket, above as [, flags[,
dont_inherit]]. Is this an optional argument like flags=dont_inherit?

Just not grokking it correctly and I can't seem to track down where the
documentation formatting is defined within the python.org documentation...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100712/5f601e0f/attachment.html>

From adam.jtm30 at gmail.com  Mon Jul 12 17:26:20 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Mon, 12 Jul 2010 16:26:20 +0100
Subject: [Tutor] Python Documentation Clarification
In-Reply-To: <AANLkTilDPc6gd0WLiOgjHKGaGbFkSdISM1bA1imNjVUu@mail.gmail.com>
References: <AANLkTikL5D727s3kCyG8W4LHnV-Gpd3BLEBZXMKJokRk@mail.gmail.com> 
	<AANLkTilDPc6gd0WLiOgjHKGaGbFkSdISM1bA1imNjVUu@mail.gmail.com>
Message-ID: <AANLkTilzo-rPV-wMAYfjQAK5WyV8vAR4171I2azdj772@mail.gmail.com>

On 12 July 2010 15:49, Huy Ton That <huyslogic at gmail.com> wrote:

> This is going to sound silly, but I realized there are some areas within
> the documentation that do not make absolute sense to me.
>
> e.g.
>
> compile(source, filename, mode[, flags[, dont_inherit]])
>
> I see within this built in function, the first argument can be what they
> define as source, the second argument as the filename and the third as the
> mode.
>
> But what confuses me is sometimes I see a bracket, above as [, flags[,
> dont_inherit]]. Is this an optional argument like flags=dont_inherit?
>
> Just not grokking it correctly and I can't seem to track down where the
> documentation formatting is defined within the python.org documentation...
>
>
You're about right really, it's a keyword argument which means it will have
a default so you can specify it or leave the default by ignoring it.

HTH,
Adam.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100712/166e603d/attachment.html>

From airscorp at otenet.gr  Mon Jul 12 17:29:47 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Mon, 12 Jul 2010 18:29:47 +0300
Subject: [Tutor] Python Documentation Clarification
In-Reply-To: <AANLkTikL5D727s3kCyG8W4LHnV-Gpd3BLEBZXMKJokRk@mail.gmail.com>
References: <AANLkTikL5D727s3kCyG8W4LHnV-Gpd3BLEBZXMKJokRk@mail.gmail.com>
Message-ID: <4C3B34EB.70306@otenet.gr>


>
> compile(source, filename, mode[, flags[, dont_inherit]])
>
> I see within this built in function, the first argument can be what 
> they define as source, the second argument as the filename and the 
> third as the mode.
>
> But what confuses me is sometimes I see a bracket, above as [, flags[, 
> dont_inherit]]. Is this an optional argument like flags=dont_inherit?
>
>
Brackets do indeed mean optional arguments.
So you can do
compile(source, filename, mode, flags=whatever, dont_inherit=True)
or something.

The nested brackets most likely show that (in your example), 
dont_inherit is optional, but can be used only if you (optionally) also 
provide the flags argument.

Of course, don't take my word for it and read the rest of the 
description in the documentation.

Also read here:
<http://docs.python.org/reference/introduction.html?highlight=brackets>http://docs.python.org/reference/introduction.html?highlight=brackets#notation

Nick

From breamoreboy at yahoo.co.uk  Mon Jul 12 17:35:30 2010
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Mon, 12 Jul 2010 16:35:30 +0100
Subject: [Tutor] Python Documentation Clarification
In-Reply-To: <AANLkTikL5D727s3kCyG8W4LHnV-Gpd3BLEBZXMKJokRk@mail.gmail.com>
References: <AANLkTikL5D727s3kCyG8W4LHnV-Gpd3BLEBZXMKJokRk@mail.gmail.com>
Message-ID: <i1fco6$uim$1@dough.gmane.org>

On 12/07/2010 15:49, Huy Ton That wrote:
> This is going to sound silly, but I realized there are some areas within the
> documentation that do not make absolute sense to me.
>
> e.g.
>
> compile(source, filename, mode[, flags[, dont_inherit]])
>
> I see within this built in function, the first argument can be what they
> define as source, the second argument as the filename and the third as the
> mode.
>
> But what confuses me is sometimes I see a bracket, above as [, flags[,
> dont_inherit]]. Is this an optional argument like flags=dont_inherit?
They are both optional arguments so you could call compile with:-
compile(source, filename, mode)
compile(source, filename, mode, flags)
compile(source, filename, mode, flags, dont_inherit)
>
> Just not grokking it correctly and I can't seem to track down where the
> documentation formatting is defined within the python.org documentation...
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

HTH.

Mark Lawrence



From smokefloat at gmail.com  Mon Jul 12 17:48:58 2010
From: smokefloat at gmail.com (David Hutto)
Date: Mon, 12 Jul 2010 11:48:58 -0400
Subject: [Tutor] Python Documentation Clarification
In-Reply-To: <AANLkTikL5D727s3kCyG8W4LHnV-Gpd3BLEBZXMKJokRk@mail.gmail.com>
References: <AANLkTikL5D727s3kCyG8W4LHnV-Gpd3BLEBZXMKJokRk@mail.gmail.com>
Message-ID: <AANLkTinrXeNIQ9Ss1PFOhtyowHos7sTUVKSjKVWO7yGA@mail.gmail.com>

On Mon, Jul 12, 2010 at 10:49 AM, Huy Ton That <huyslogic at gmail.com> wrote:
> This is going to sound silly, but I realized there are some areas within the
> documentation that do not make absolute sense to me.
> e.g.
> compile(source, filename, mode[, flags[, dont_inherit]])
> I see within this built in function, the first argument can be what they
> define as source, the second argument as the filename and the third as the
> mode.
> But what confuses me is sometimes I see a bracket, above as [, flags[,
> dont_inherit]]. Is this an optional argument like flags=dont_inherit?
> Just not grokking it correctly and I can't seem to track down where the
> documentation formatting is defined within the python.org documentation...
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

From

http://docs.python.org/tutorial/datastructures.html

is this :
'(The square brackets around the i in the method signature denote that
the parameter is optional, not that you should type square brackets at
that position. You will see this notation frequently in the Python
Library Reference.)'

From huyslogic at gmail.com  Mon Jul 12 17:50:32 2010
From: huyslogic at gmail.com (Huy Ton That)
Date: Mon, 12 Jul 2010 11:50:32 -0400
Subject: [Tutor] Python Documentation Clarification
In-Reply-To: <4C3B34EB.70306@otenet.gr>
References: <AANLkTikL5D727s3kCyG8W4LHnV-Gpd3BLEBZXMKJokRk@mail.gmail.com> 
	<4C3B34EB.70306@otenet.gr>
Message-ID: <AANLkTilGXS9jj4cUOXTGCwMSv2Xh856hPzcUllIz3QoM@mail.gmail.com>

Proverbial Ah-ha moment all. This clarifies things greatly (:

Thanks you all!!

On Mon, Jul 12, 2010 at 11:29 AM, Nick Raptis <airscorp at otenet.gr> wrote:

>
>
>> compile(source, filename, mode[, flags[, dont_inherit]])
>>
>> I see within this built in function, the first argument can be what they
>> define as source, the second argument as the filename and the third as the
>> mode.
>>
>> But what confuses me is sometimes I see a bracket, above as [, flags[,
>> dont_inherit]]. Is this an optional argument like flags=dont_inherit?
>>
>>
>>  Brackets do indeed mean optional arguments.
> So you can do
> compile(source, filename, mode, flags=whatever, dont_inherit=True)
> or something.
>
> The nested brackets most likely show that (in your example), dont_inherit
> is optional, but can be used only if you (optionally) also provide the flags
> argument.
>
> Of course, don't take my word for it and read the rest of the description
> in the documentation.
>
> Also read here:
> <http://docs.python.org/reference/introduction.html?highlight=brackets>
> http://docs.python.org/reference/introduction.html?highlight=brackets#notation
>
> Nick
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100712/2af50a1a/attachment.html>

From alan.gauld at btinternet.com  Mon Jul 12 20:46:45 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 12 Jul 2010 19:46:45 +0100
Subject: [Tutor] Python Documentation Clarification
References: <AANLkTikL5D727s3kCyG8W4LHnV-Gpd3BLEBZXMKJokRk@mail.gmail.com>
Message-ID: <i1fnug$8v6$1@dough.gmane.org>


"Huy Ton That" <huyslogic at gmail.com> wrote

> Just not grokking it correctly and I can't seem to track down where 
> the
> documentation formatting is defined within the python.org 
> documentation...

It is confusing I agree, but the style goes back to the dawn of
computing - certainly further back than me! I remember seeing
CP/M commands documented in that same style back in the very
early 1980's and MS-DOS was done that way too.
(In fact if you use DOS Help it still is... try typing HELP DIR...)


Alan G. 



From delegbede at dudupay.com  Mon Jul 12 21:22:52 2010
From: delegbede at dudupay.com (Dipo Elegbede)
Date: Mon, 12 Jul 2010 20:22:52 +0100
Subject: [Tutor] module for fingerprint and pictures
Message-ID: <AANLkTimID-gEtmLT1jGAheBDSLT7GblettvviYbCKcyc@mail.gmail.com>

Hello people,

I am working on an interface that is supposed to interact with a webcam and
capture pictures into a database and also fingerprint from a fingerprint
hardware.

Is there any python module or library I can work with.

I need suggestions, assistance and information where necessary.

To be truthful, I need to do a demo for that app and then go commercial if
my project impresses the client.

Please help me.

-- 
Elegbede Muhammed Oladipupo
OCA
+2348077682428
+2347042171716
www.dudupay.com
Mobile Banking Solutions | Transaction Processing | Enterprise Application
Development
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100712/2127088e/attachment.html>

From emile at fenx.com  Mon Jul 12 21:47:46 2010
From: emile at fenx.com (Emile van Sebille)
Date: Mon, 12 Jul 2010 12:47:46 -0700
Subject: [Tutor] module for fingerprint and pictures
In-Reply-To: <AANLkTimID-gEtmLT1jGAheBDSLT7GblettvviYbCKcyc@mail.gmail.com>
References: <AANLkTimID-gEtmLT1jGAheBDSLT7GblettvviYbCKcyc@mail.gmail.com>
Message-ID: <i1frjr$mf8$1@dough.gmane.org>

On 7/12/2010 12:22 PM Dipo Elegbede said...
> Hello people,
>
> I am working on an interface that is supposed to interact with a webcam and
> capture pictures into a database and also fingerprint from a fingerprint
> hardware.

I've done this a couple different times now, one time using panasonic 
webcams pushing out ftp images once a second and capturing validated 
fingerprints on a biometric timeclock from acroprint.

>
> Is there any python module or library I can work with.

Not that I found.

>
> I need suggestions, assistance and information where necessary.
>
> To be truthful, I need to do a demo for that app and then go commercial if
> my project impresses the client.

What's the app going to do?

Emile



From siren99 at yahoo.com  Tue Jul 13 00:19:51 2010
From: siren99 at yahoo.com (Siren Saren)
Date: Mon, 12 Jul 2010 15:19:51 -0700 (PDT)
Subject: [Tutor] Request for help learning the right way to deal with lists
	in lists
In-Reply-To: <mailman.2673.1278948588.1671.tutor@python.org>
Message-ID: <359328.83032.qm@web44711.mail.sp1.yahoo.com>

I'm still fairly new to programming.? Python is my first language and I am teaching myself as best I can.? I'm struggling with a situation that I expect must come up all the time.? I can come up with relatively complicated solutions but I wonder if there's not a more pythonic way of doing it.

I've seen a lot of examples in books for dealing with lists of alternating data types, but what about a list that doesn't follow a simple numeric pattern?? For example, say I have a list that's a composite of two elements: books and key pages / albums and favorite tracks / medicines and times taken, whatever.? To make a program that does something to the first set of elements based on the second set of elements, what kind of structure should I set up?? 

Probably easier to choose one of these.? So pretend I have a list like this:

(Crime and punishment, page 10, page 40, page 30, Brother's Karamazov, page 22, page 55, page 9000, Father's and Sons, page 100, Anna Karenina, page 1, page 2, page 4, page 7, page 9)

Since I can identify the elements and since I know the values are 'in order,' in other words the page numbers between the first and second book all belong to the first book, I can make a mapping.? But I've been surprised at the complexity.? So in this hypothetical, with a regular expression, I can easily convert the pages to integers, and identify the two lists.? But what's the right way to map them to each other, if I am planning to, for example, tear out these key pages and make a wall hanging.? (I would never do this with precious books like these, of course).? Am I right to think that I want to get them into a form that clearly relates them to each other from the outset?? Does a dictionary make sense-- I've read that I should expect to put a lot of my data into dictionaries?

My tentative approach has been as follows:

a. Make a sublist of the Books.? Here we could just get the non-integers so Books = ('C and P', 'Brothers K' ...)
b. Look each up book in the main list to get an index values
c.? Now my approach becomes ugly.? In pseudo code-

For book in Books:
??? A dictionary should map the book to a list of all the elements in the main list that fall between the book's index value and the next book's index value

I keep coming up with embedded loops to express this but I simultaneously feel like I am missing a third layer (somehow maybe it's 'for book,' 'for index,' 'for element'?) and like Occham is going to come by with his razor and laugh at me and say, "oh there's a function that does this called the "one to many mapping function."? 

I think I'm reading the right books and going to the right web pages and such to learn, but in this case, I must have just not comprehended.? Would be grateful for any input.? Have enjoyed reading the archives of this group as I've been trying to get my head around programming.? Thanks again

Soren

--- On Mon, 7/12/10, tutor-request at python.org <tutor-request at python.org> wrote:

From: tutor-request at python.org <tutor-request at python.org>
Subject: Tutor Digest, Vol 77, Issue 32
To: tutor at python.org
Date: Monday, July 12, 2010, 3:29 PM

Send Tutor mailing list submissions to
??? tutor at python.org

To subscribe or unsubscribe via the World Wide Web, visit
??? http://mail.python.org/mailman/listinfo/tutor
or, via email, send a message with subject or body 'help' to
??? tutor-request at python.org

You can reach the person managing the list at
??? tutor-owner at python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."


Today's Topics:

???1. Re: extract a submatrix (Eike Welk)
???2. Re: extract a submatrix (Dave Angel)
???3. Re: extract a submatrix (Bala subramanian)
???4. Python Documentation Clarification (Huy Ton That)
???5. Re: Python Documentation Clarification (Adam Bark)
???6. Re: Python Documentation Clarification (Nick Raptis)


----------------------------------------------------------------------

Message: 1
Date: Mon, 12 Jul 2010 12:03:22 +0200
From: Eike Welk <eike.welk at gmx.net>
To: tutor at python.org
Subject: Re: [Tutor] extract a submatrix
Message-ID: <201007121203.22922.eike.welk at gmx.net>
Content-Type: Text/Plain;? charset="iso-8859-15"

Hello Bala!

On Sunday July 11 2010 23:41:14 Bala subramanian wrote:
> I have a
> matrix of size 550,550. I want to extract only part of this matrix say
>? first 330 elements, i dnt need the last 220 elements in the matrix. is
>? there any function in numpy that can do this kind of extraction.

I demonstrate it with a integer matrix of dimension (5, 10):

In [3]: a = array(range(50)).reshape(5,10)

In [4]: a
Out[4]:
array([[ 0,? 1,? 2,? 3,? 4,? 5,? 6,? 7,? 8,? 9],
? ? ???[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
? ? ???[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
? ? ???[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
? ? ???[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])

In [5]: a[:, 0:7]
Out[5]:
array([[ 0,? 1,? 2,? 3,? 4,? 5,? 6],
? ? ???[10, 11, 12, 13, 14, 15, 16],
? ? ???[20, 21, 22, 23, 24, 25, 26],
? ? ???[30, 31, 32, 33, 34, 35, 36],
? ? ???[40, 41, 42, 43, 44, 45, 46]])

In [6]: a[:, 7:]
Out[6]:
array([[ 7,? 8,? 9],
? ? ???[17, 18, 19],
? ? ???[27, 28, 29],
? ? ???[37, 38, 39],
? ? ???[47, 48, 49]])


The colons ":" denote slices. In a 2D array you can have slices in two 
dimensions. in the first dimension (downwards) I always select all elements. 
A good explanation of slices is here:
http://tiny.cc/ohl2g
http://stackoverflow.com/questions/509211/good-primer-for-python-slice-
notation

A nice list of Numpy's many functions and methods is here: (This is the Numpy 
page I use most often.)
http://tiny.cc/qzwoq
http://www.scipy.org/Numpy_Example_List_With_Doc#head-11717acafb821da646a8db6997e59b820ac8761a

The funny prompt is from IPython (ipython --pylab), a program that enhances 
Python's interactive mode, and keeps Matplotlib graphs alive.


Eike.


------------------------------

Message: 2
Date: Mon, 12 Jul 2010 07:17:13 -0400
From: Dave Angel <davea at ieee.org>
To: Bala subramanian <bala.biophysics at gmail.com>
Cc: tutor at python.org
Subject: Re: [Tutor] extract a submatrix
Message-ID: <4C3AF9B9.2050101 at ieee.org>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed



Bala subramanian wrote:
> Friends,
> Excuse me if this question is not appropriate for this forum. I have a
> matrix of size 550,550. I want to extract only part of this matrix say first
> 330 elements, i dnt need the last 220 elements in the matrix. is there any
> function in numpy that can do this kind of extraction. I am quite new to
> numpy. How can do the same ?
>
> Thank you,
> Bala
>
>???
I don't know numpy, and it probably would be better to use that forum.? 
But there are several people here who do, and one of them will probably 
help.

However, I would point out that if you fetch the first 220 elements of a 
550x550 matrix, you'll have 302170 elements left.

DaveA



------------------------------

Message: 3
Date: Mon, 12 Jul 2010 15:38:36 +0200
From: Bala subramanian <bala.biophysics at gmail.com>
To: Dave Angel <davea at ieee.org>, tutor at python.org
Subject: Re: [Tutor] extract a submatrix
Message-ID:
??? <AANLkTikCw1ekYksYvGUjxJT6TgoCNvIZjFtH3r_3owlB at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

Dear Eike,
Thank you so much, the simple slicing operation solved my problem. Thank you
for the links, i am just going through the same.

Dave
I wanted was to extract a matrix of dimension 330,330 from a matrix of
dimension 550,550. Sorry if my previous post was not clear. I am able to do
it by slicing as suggested by Eike.

Thank you,
Bala

On Mon, Jul 12, 2010 at 1:17 PM, Dave Angel <davea at ieee.org> wrote:

>
>
> Bala subramanian wrote:
>
>> Friends,
>> Excuse me if this question is not appropriate for this forum. I have a
>> matrix of size 550,550. I want to extract only part of this matrix say
>> first
>> 330 elements, i dnt need the last 220 elements in the matrix. is there any
>> function in numpy that can do this kind of extraction. I am quite new to
>> numpy. How can do the same ?
>>
>> Thank you,
>> Bala
>>
>>
>>
> I don't know numpy, and it probably would be better to use that forum.? But
> there are several people here who do, and one of them will probably help.
>
> However, I would point out that if you fetch the first 220 elements of a
> 550x550 matrix, you'll have 302170 elements left.
>
> DaveA
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100712/7c47092c/attachment-0001.html>

------------------------------

Message: 4
Date: Mon, 12 Jul 2010 10:49:04 -0400
From: Huy Ton That <huyslogic at gmail.com>
To: tutor at python.org
Subject: [Tutor] Python Documentation Clarification
Message-ID:
??? <AANLkTikL5D727s3kCyG8W4LHnV-Gpd3BLEBZXMKJokRk at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

This is going to sound silly, but I realized there are some areas within the
documentation that do not make absolute sense to me.

e.g.

compile(source, filename, mode[, flags[, dont_inherit]])

I see within this built in function, the first argument can be what they
define as source, the second argument as the filename and the third as the
mode.

But what confuses me is sometimes I see a bracket, above as [, flags[,
dont_inherit]]. Is this an optional argument like flags=dont_inherit?

Just not grokking it correctly and I can't seem to track down where the
documentation formatting is defined within the python.org documentation...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100712/5f601e0f/attachment-0001.html>

------------------------------

Message: 5
Date: Mon, 12 Jul 2010 16:26:20 +0100
From: Adam Bark <adam.jtm30 at gmail.com>
To: tutor-python <Tutor at python.org>
Subject: Re: [Tutor] Python Documentation Clarification
Message-ID:
??? <AANLkTilzo-rPV-wMAYfjQAK5WyV8vAR4171I2azdj772 at mail.gmail.com>
Content-Type: text/plain; charset="utf-8"

On 12 July 2010 15:49, Huy Ton That <huyslogic at gmail.com> wrote:

> This is going to sound silly, but I realized there are some areas within
> the documentation that do not make absolute sense to me.
>
> e.g.
>
> compile(source, filename, mode[, flags[, dont_inherit]])
>
> I see within this built in function, the first argument can be what they
> define as source, the second argument as the filename and the third as the
> mode.
>
> But what confuses me is sometimes I see a bracket, above as [, flags[,
> dont_inherit]]. Is this an optional argument like flags=dont_inherit?
>
> Just not grokking it correctly and I can't seem to track down where the
> documentation formatting is defined within the python.org documentation...
>
>
You're about right really, it's a keyword argument which means it will have
a default so you can specify it or leave the default by ignoring it.

HTH,
Adam.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100712/166e603d/attachment-0001.html>

------------------------------

Message: 6
Date: Mon, 12 Jul 2010 18:29:47 +0300
From: Nick Raptis <airscorp at otenet.gr>
To: tutor at python.org
Subject: Re: [Tutor] Python Documentation Clarification
Message-ID: <4C3B34EB.70306 at otenet.gr>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed


>
> compile(source, filename, mode[, flags[, dont_inherit]])
>
> I see within this built in function, the first argument can be what 
> they define as source, the second argument as the filename and the 
> third as the mode.
>
> But what confuses me is sometimes I see a bracket, above as [, flags[, 
> dont_inherit]]. Is this an optional argument like flags=dont_inherit?
>
>
Brackets do indeed mean optional arguments.
So you can do
compile(source, filename, mode, flags=whatever, dont_inherit=True)
or something.

The nested brackets most likely show that (in your example), 
dont_inherit is optional, but can be used only if you (optionally) also 
provide the flags argument.

Of course, don't take my word for it and read the rest of the 
description in the documentation.

Also read here:
<http://docs.python.org/reference/introduction.html?highlight=brackets>http://docs.python.org/reference/introduction.html?highlight=brackets#notation

Nick


------------------------------

_______________________________________________
Tutor maillist? -? Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


End of Tutor Digest, Vol 77, Issue 32
*************************************



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100712/acf9ce67/attachment-0001.html>

From steve at pearwood.info  Tue Jul 13 02:40:21 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 13 Jul 2010 10:40:21 +1000
Subject: [Tutor] Request for help learning the right way to deal with
	lists in lists
In-Reply-To: <359328.83032.qm@web44711.mail.sp1.yahoo.com>
References: <359328.83032.qm@web44711.mail.sp1.yahoo.com>
Message-ID: <201007131040.21555.steve@pearwood.info>

On Tue, 13 Jul 2010 08:19:51 am Siren Saren wrote:
> I'm still fairly new to programming.
[...]

Please don't include the ENTIRE 300+ lines of the digest in your post. 
Start a NEW email, don't reply to the digest, and if you absolutely 
have to reply to the digest, delete the parts that you are not directly 
replying to.

> I've seen a lot of examples in books for dealing with lists of
> alternating data types, but what about a list that doesn't follow a
> simple numeric pattern?? 

The general solution to that is, avoid it.


[...]
> Probably easier to choose one of these.? So pretend I have a list
> like this:
>
> (Crime and punishment, page 10, page 40, page 30, Brother's
> Karamazov, page 22, page 55, page 9000, Father's and Sons, page 100,
> Anna Karenina, page 1, page 2, page 4, page 7, page 9)

The simplest way to deal with that is to put the pages into sub-lists, 
and combine the title and pages into a tuple:

booklist = [
 ("Crime and punishment", [10, 40, 30]),
 ("Brother's Karamazov", [22, 55, 9000]),  # That's a big book!
 ("Father's and Sons", [100]),
 ("Anna Karenina", [1, 2, 4, 7, 9]),
]

Now you can iterate over the collection:

for title, pages in booklist:
    print title
    for page in pages:
        print "page", page


or do whatever other work you need on them. Notice that the outer list 
is now easy to work with: every element of the outer list is the same, 
a tuple of two items. The inner lists are also easy to deal with: every 
element is simply a page number.

An alternative is a dictionary:

books = {
 "Crime and punishment": [10, 40, 30],
 "Brother's Karamazov": [22, 55, 9000],
 "Father's and Sons": [100],
 "Anna Karenina": [1, 2, 4, 7, 9],
 "Where's Wally?": [],
}

Now each key is simply the title, and the value is a list of page 
numbers.


-- 
Steven D'Aprano

From ehamiter at gmail.com  Tue Jul 13 03:45:03 2010
From: ehamiter at gmail.com (Eric Hamiter)
Date: Mon, 12 Jul 2010 20:45:03 -0500
Subject: [Tutor] Request for help learning the right way to deal with
	lists in lists
In-Reply-To: <359328.83032.qm@web44711.mail.sp1.yahoo.com>
References: <mailman.2673.1278948588.1671.tutor@python.org> 
	<359328.83032.qm@web44711.mail.sp1.yahoo.com>
Message-ID: <AANLkTikWDDlO5yyAW-v1CdxEqfYWQ8kWL9RVzuEefDIC@mail.gmail.com>

I'm fairly new to programming and Python as well, but I have a suggestion
that may be worth looking into-- are you familiar with pickling? It sounds
like something that may fit in well with what you're trying to do.

Good reference article:

http://articles.techrepublic.com.com/5100-10878_11-1052190.html


On Mon, Jul 12, 2010 at 5:19 PM, Siren Saren <siren99 at yahoo.com> wrote:

> I'm still fairly new to programming.  Python is my first language and I am
> teaching myself as best I can.  I'm struggling with a situation that I
> expect must come up all the time.  I can come up with relatively complicated
> solutions but I wonder if there's not a more pythonic way of doing it.
>
> I've seen a lot of examples in books for dealing with lists of alternating
> data types, but what about a list that doesn't follow a simple numeric
> pattern?  For example, say I have a list that's a composite of two elements:
> books and key pages / albums and favorite tracks / medicines and times
> taken, whatever.  To make a program that does something to the first set of
> elements based on the second set of elements, what kind of structure should
> I set up?
>
> Probably easier to choose one of these.  So pretend I have a list like
> this:
>
> (Crime and punishment, page 10, page 40, page 30, Brother's Karamazov, page
> 22, page 55, page 9000, Father's and Sons, page 100, Anna Karenina, page 1,
> page 2, page 4, page 7, page 9)
>
> Since I can identify the elements and since I know the values are 'in
> order,' in other words the page numbers between the first and second book
> all belong to the first book, I can make a mapping.  But I've been surprised
> at the complexity.  So in this hypothetical, with a regular expression, I
> can easily convert the pages to integers, and identify the two lists.  But
> what's the right way to map them to each other, if I am planning to, for
> example, tear out these key pages and make a wall hanging.  (I would never
> do this with precious books like these, of course).  Am I right to think
> that I want to get them into a form that clearly relates them to each other
> from the outset?  Does a dictionary make sense-- I've read that I should
> expect to put a lot of my data into dictionaries?
>
> My tentative approach has been as follows:
>
> a. Make a sublist of the Books.  Here we could just get the non-integers so
> Books = ('C and P', 'Brothers K' ...)
> b. Look each up book in the main list to get an index values
> c.  Now my approach becomes ugly.  In pseudo code-
>
> For book in Books:
>     A dictionary should map the book to a list of all the elements in the
> main list that fall between the book's index value and the next book's index
> value
>
> I keep coming up with embedded loops to express this but I simultaneously
> feel like I am missing a third layer (somehow maybe it's 'for book,' 'for
> index,' 'for element'?) and like Occham is going to come by with his razor
> and laugh at me and say, "oh there's a function that does this called the
> "one to many mapping function."
>
> I think I'm reading the right books and going to the right web pages and
> such to learn, but in this case, I must have just not comprehended.  Would
> be grateful for any input.  Have enjoyed reading the archives of this group
> as I've been trying to get my head around programming.  Thanks again
>
> Soren
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100712/ced8ec5b/attachment.html>

From smokefloat at gmail.com  Tue Jul 13 04:12:47 2010
From: smokefloat at gmail.com (David Hutto)
Date: Mon, 12 Jul 2010 22:12:47 -0400
Subject: [Tutor] Request for help learning the right way to deal with
	lists in lists
In-Reply-To: <AANLkTikWDDlO5yyAW-v1CdxEqfYWQ8kWL9RVzuEefDIC@mail.gmail.com>
References: <mailman.2673.1278948588.1671.tutor@python.org>
	<359328.83032.qm@web44711.mail.sp1.yahoo.com>
	<AANLkTikWDDlO5yyAW-v1CdxEqfYWQ8kWL9RVzuEefDIC@mail.gmail.com>
Message-ID: <AANLkTikD2fhk1C-PEyPDirqwBZ8-qq_gcvdQJ5JcYcwD@mail.gmail.com>

On Mon, Jul 12, 2010 at 9:45 PM, Eric Hamiter <ehamiter at gmail.com> wrote:

> I'm fairly new to programming and Python as well, but I have a suggestion
> that may be worth looking into-- are you familiar with pickling? It sounds
> like something that may fit in well with what you're trying to do.
>
> Good reference article:
>
> http://articles.techrepublic.com.com/5100-10878_11-1052190.html
>
>
> I'm new to python too, but I'd suggest using sqlite ,and entering uploading
the specific pages as text files, and then calling them from the name and
stored file their listed as being in in the db. As it seems now, you're just
listing book names and numbers(or maybe I didn't read more into what you
want to do).


>
> On Mon, Jul 12, 2010 at 5:19 PM, Siren Saren <siren99 at yahoo.com> wrote:
>
>> I'm still fairly new to programming.  Python is my first language and I am
>> teaching myself as best I can.  I'm struggling with a situation that I
>> expect must come up all the time.  I can come up with relatively complicated
>> solutions but I wonder if there's not a more pythonic way of doing it.
>>
>> I've seen a lot of examples in books for dealing with lists of alternating
>> data types, but what about a list that doesn't follow a simple numeric
>> pattern?  For example, say I have a list that's a composite of two elements:
>> books and key pages / albums and favorite tracks / medicines and times
>> taken, whatever.  To make a program that does something to the first set of
>> elements based on the second set of elements, what kind of structure should
>> I set up?
>>
>> Probably easier to choose one of these.  So pretend I have a list like
>> this:
>>
>> (Crime and punishment, page 10, page 40, page 30, Brother's Karamazov,
>> page 22, page 55, page 9000, Father's and Sons, page 100, Anna Karenina,
>> page 1, page 2, page 4, page 7, page 9)
>>
>> Since I can identify the elements and since I know the values are 'in
>> order,' in other words the page numbers between the first and second book
>> all belong to the first book, I can make a mapping.  But I've been surprised
>> at the complexity.  So in this hypothetical, with a regular expression, I
>> can easily convert the pages to integers, and identify the two lists.  But
>> what's the right way to map them to each other, if I am planning to, for
>> example, tear out these key pages and make a wall hanging.  (I would never
>> do this with precious books like these, of course).  Am I right to think
>> that I want to get them into a form that clearly relates them to each other
>> from the outset?  Does a dictionary make sense-- I've read that I should
>> expect to put a lot of my data into dictionaries?
>>
>> My tentative approach has been as follows:
>>
>> a. Make a sublist of the Books.  Here we could just get the non-integers
>> so Books = ('C and P', 'Brothers K' ...)
>> b. Look each up book in the main list to get an index values
>> c.  Now my approach becomes ugly.  In pseudo code-
>>
>> For book in Books:
>>     A dictionary should map the book to a list of all the elements in the
>> main list that fall between the book's index value and the next book's index
>> value
>>
>> I keep coming up with embedded loops to express this but I simultaneously
>> feel like I am missing a third layer (somehow maybe it's 'for book,' 'for
>> index,' 'for element'?) and like Occham is going to come by with his razor
>> and laugh at me and say, "oh there's a function that does this called the
>> "one to many mapping function."
>>
>> I think I'm reading the right books and going to the right web pages and
>> such to learn, but in this case, I must have just not comprehended.  Would
>> be grateful for any input.  Have enjoyed reading the archives of this group
>> as I've been trying to get my head around programming.  Thanks again
>>
>> Soren
>>
>>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100712/31850423/attachment-0001.html>

From delegbede at dudupay.com  Tue Jul 13 08:13:31 2010
From: delegbede at dudupay.com (Dipo Elegbede)
Date: Tue, 13 Jul 2010 07:13:31 +0100
Subject: [Tutor] LOCATION ISSUES
Message-ID: <AANLkTikmArXMy02yMv3st3-4QSqVc6HaVudrPNOUL3VP@mail.gmail.com>

Hello All,

Kindly help me with the location for the files created by this codes.

I have already compiled the codes and it has no error.

I copied the code from the following url:
http://www.pythonware.com/library/pil/handbook/image.htm

This is supposed to create thumbnails of picture in the directory where I
saved my file.

Please Help.

Thank You.

-- 
Elegbede Muhammed Oladipupo
OCA
+2348077682428
+2347042171716
www.dudupay.com
Mobile Banking Solutions | Transaction Processing | Enterprise Application
Development
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100713/17362b0c/attachment.html>

From emile at fenx.com  Tue Jul 13 08:27:11 2010
From: emile at fenx.com (Emile van Sebille)
Date: Mon, 12 Jul 2010 23:27:11 -0700
Subject: [Tutor] LOCATION ISSUES
In-Reply-To: <AANLkTikmArXMy02yMv3st3-4QSqVc6HaVudrPNOUL3VP@mail.gmail.com>
References: <AANLkTikmArXMy02yMv3st3-4QSqVc6HaVudrPNOUL3VP@mail.gmail.com>
Message-ID: <i1h12n$oon$1@dough.gmane.org>

On 7/12/2010 11:13 PM Dipo Elegbede said...
> Hello All,
>
> Kindly help me with the location for the files created by this codes.
>
> I have already compiled the codes and it has no error.
>
> I copied the code from the following url:
> http://www.pythonware.com/library/pil/handbook/image.htm
>
> This is supposed to create thumbnails of picture in the directory where I
> saved my file.

Which is what it will do when python is started from that directory.

How are you starting python?

Emile


From delegbede at dudupay.com  Tue Jul 13 08:52:20 2010
From: delegbede at dudupay.com (Dipo Elegbede)
Date: Tue, 13 Jul 2010 07:52:20 +0100
Subject: [Tutor] LOCATION ISSUES
In-Reply-To: <i1h12n$oon$1@dough.gmane.org>
References: <AANLkTikmArXMy02yMv3st3-4QSqVc6HaVudrPNOUL3VP@mail.gmail.com>
	<i1h12n$oon$1@dough.gmane.org>
Message-ID: <AANLkTimE0avkwqERd2wGI_YXvXbMAFlOytRFQU4dk9Z2@mail.gmail.com>

>
> Which is what it will do when python is started from that directory.
>
> I actually found the copies that were made by the code in the same
> directory but found out that they all had a .thumbnail ext which would not
> open and it is understandable.
>
> I have however chaged that part of the code to carry .jpg hoping to let it
> make thumbnails with jpg extensions.
>
>>
>> How are you starting python?
>>
>
> I am new to python. I have basic understanding about manipulating strings,
> variables, lists, tuples, dictionary and all. I read along the Line as I do
> stuff. I am however adopting this method of taking up bigger project to make
> the process faster. I might be wrong though.
>
> I am expected to take up certain projects and so I hope to catch up as fast
> as I can. Where I run into troubles, I'd come back here truthfully. as soon
> as I am going commercial, I hope to also mention it here that it is
> commercial so if any assistance would carry financial impliccations, it
> could be discussed.
>
> I hope you understand it now.
>
> Thanks.
>
>>
>> Emile
>>
>>
>> --
>> Elegbede Muhammed Oladipupo
>> OCA
>> +2348077682428
>> +2347042171716
>> www.dudupay.com
>> Mobile Banking Solutions | Transaction Processing | Enterprise Application
>> Development
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100713/d8dfc1d1/attachment.html>

From alan.gauld at btinternet.com  Tue Jul 13 09:35:45 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 13 Jul 2010 08:35:45 +0100
Subject: [Tutor] Request for help learning the right way to deal with
	listsin lists
References: <mailman.2673.1278948588.1671.tutor@python.org>
	<359328.83032.qm@web44711.mail.sp1.yahoo.com>
Message-ID: <i1h50d$4vu$1@dough.gmane.org>


"Siren Saren" <siren99 at yahoo.com> wrote
> say I have a list that's a composite of two elements:
> books and key pages / albums and favorite tracks /
> medicines and times taken, whatever.

Thats a good scenario for using a dictionary containing
a list or tuple per key.

> To make a program that does something to the
> first set of elements based on the second set of elements,

I'm not quite sure what you mean by this though...?

> if I am planning to, for example, tear out these key
> pages and make a wall hanging. Am I right to think
> that I want to get them into a form that clearly relates
> them to each other from the outset?

Yes, you should always try to find a data structure that
reflects the problem. It will naturally lead to simpler algorithms
and cleaner code.

> Does a dictionary make sense-- I've read that I should
> expect to put a lot of my data into dictionaries?

Yes a dictionary is a good structure for random lookups
based on a unique key that returns related data.

> a. Make a sublist of the Books.

You don't need a sublist, just use the dictionary.

> b. Look each up book in the main list to get an index values

You don't need index values, just use the dictionary directly.

> For book in Books:
> A dictionary should map the book to a list of all the elements
> in the main list that fall between the book's index value and
> the next book's index value

The dictionary returns the list of pages directly.

> I keep coming up with embedded loops to express this
> but I simultaneously feel like I am missing a third layer

You need a loop over the dictionary and possibly a loop over the 
pages:

for book, pages in Books.items():
    print book
    for page in pages:
         print 'page: ', page

If the data gets more complex you could put the data into a class:

class Book:
      def __init__(self, title, pages=[]):
          self.title = title
          self.pages = pages

Books = [ Book('War & Peace", [3,56,88]),
               Book("Huck Finn", [2,5,19]) ]

for book in Books:
     print book.title, book.pages

Thre are many options, you need to decide which best suits your 
problem.

HTH,


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






From delegbede at dudupay.com  Tue Jul 13 11:50:28 2010
From: delegbede at dudupay.com (Dipo Elegbede)
Date: Tue, 13 Jul 2010 10:50:28 +0100
Subject: [Tutor] Help
Message-ID: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>

I was trying to write a code that prints prime numbers between 1 and 20.

I have by myself seen that something is wrong with my code and also my
brain.

Could anyone be kind enough to tell me what to do....

Where I am confused is how to test for other numbers without one and the
number itself. It turns out that all numbers pass the condition I set so
that would presuppose that all numbers are prime which is not.

How exactly can I get it to run checks with other numbers such that it
doesn't include the number itself and 1.

The code is as follows:

for i in range(1,20):

    if float(i) % 1 == 0 and float(i) % i == 0:
        print i, 'is a prime number'


-- 
Elegbede Muhammed Oladipupo
OCA
+2348077682428
+2347042171716
www.dudupay.com
Mobile Banking Solutions | Transaction Processing | Enterprise Application
Development
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100713/a3b91d13/attachment.html>

From nitinpawar432 at gmail.com  Tue Jul 13 12:08:32 2010
From: nitinpawar432 at gmail.com (Nitin Pawar)
Date: Tue, 13 Jul 2010 15:38:32 +0530
Subject: [Tutor] Help
In-Reply-To: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
Message-ID: <AANLkTimjICFbiuE10lUhsIPD8Xfd0XjFpvuXUqYGeHaS@mail.gmail.com>

Hi,

You have two different problems
1) Easiest algorithm to find a prime number
2) and then coding the algorithm

By my knowledge,The Sieve of Eratosthenes algorithm is the fastest to find a
prime number.
The algorithm works on the basis that if a number n is prime, then all
multiples of it are not prime

so based on that you can code

Thanks,
Nitin


On Tue, Jul 13, 2010 at 3:20 PM, Dipo Elegbede <delegbede at dudupay.com>wrote:

> I was trying to write a code that prints prime numbers between 1 and 20.
>
> I have by myself seen that something is wrong with my code and also my
> brain.
>
> Could anyone be kind enough to tell me what to do....
>
> Where I am confused is how to test for other numbers without one and the
> number itself. It turns out that all numbers pass the condition I set so
> that would presuppose that all numbers are prime which is not.
>
> How exactly can I get it to run checks with other numbers such that it
> doesn't include the number itself and 1.
>
> The code is as follows:
>
> for i in range(1,20):
>
>     if float(i) % 1 == 0 and float(i) % i == 0:
>         print i, 'is a prime number'
>
>
> --
> Elegbede Muhammed Oladipupo
> OCA
> +2348077682428
> +2347042171716
> www.dudupay.com
> Mobile Banking Solutions | Transaction Processing | Enterprise Application
> Development
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Nitin Pawar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100713/f95e04b9/attachment.html>

From andreengels at gmail.com  Tue Jul 13 12:22:40 2010
From: andreengels at gmail.com (Andre Engels)
Date: Tue, 13 Jul 2010 12:22:40 +0200
Subject: [Tutor] Help
In-Reply-To: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
Message-ID: <AANLkTilRgj1K6UXXc_LIfhM7UZWKk_QOkoFXwklgiw7w@mail.gmail.com>

On Tue, Jul 13, 2010 at 11:50 AM, Dipo Elegbede <delegbede at dudupay.com> wrote:
> I was trying to write a code that prints prime numbers between 1 and 20.
>
> I have by myself seen that something is wrong with my code and also my
> brain.
>
> Could anyone be kind enough to tell me what to do....
>
> Where I am confused is how to test for other numbers without one and the
> number itself. It turns out that all numbers pass the condition I set so
> that would presuppose that all numbers are prime which is not.
>
> How exactly can I get it to run checks with other numbers such that it
> doesn't include the number itself and 1.
>
> The code is as follows:
>
> for i in range(1,20):
>
> ??? if float(i) % 1 == 0 and float(i) % i == 0:
> ??????? print i, 'is a prime number'

Your code only checks whether the number divides by 1 and itself. It
should check the numbers in between, and if _any_ divides the number,
decide it is not a prime number. This is best done in a separate
function (note: I am writing it here for clarity of the underlying
algorithm, there are various ways in which it could be made faster,
shorter or more Pythonic):

def isPrime(n):
    divisorFound = False
    for i in xrange(2, n):
        if n % i == 0:
            divisorFound = True
    return not divisorFound     # divisorFound is true if and only if
there is a number i (1<i<n) with n % i == 0

for i in range(2,20):
    if isPrime(i):
        print i, 'is a prime number'

By the way, do note that your cast to float is not a good idea. It
probably won't hurt you in this case, but it definitely won't improve
things. You'd much rather check exact equality with integers than with
floats.

-- 
Andr? Engels, andreengels at gmail.com

From nitinpawar432 at gmail.com  Tue Jul 13 12:34:13 2010
From: nitinpawar432 at gmail.com (Nitin Pawar)
Date: Tue, 13 Jul 2010 16:04:13 +0530
Subject: [Tutor] Help
In-Reply-To: <AANLkTilRgj1K6UXXc_LIfhM7UZWKk_QOkoFXwklgiw7w@mail.gmail.com>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
	<AANLkTilRgj1K6UXXc_LIfhM7UZWKk_QOkoFXwklgiw7w@mail.gmail.com>
Message-ID: <AANLkTik0h0FdtyvS9HDvc861muXF6iqmZEIJQEq0RlRx@mail.gmail.com>

Adding to what Andre said,

another way of optimizing the problem would be
storing the prime number in the range you want to check an array and see if
the given number is divisible by any of those prime number

This improves the performance.

Thanks,
nitin

On Tue, Jul 13, 2010 at 3:52 PM, Andre Engels <andreengels at gmail.com> wrote:

> On Tue, Jul 13, 2010 at 11:50 AM, Dipo Elegbede <delegbede at dudupay.com>
> wrote:
> > I was trying to write a code that prints prime numbers between 1 and 20.
> >
> > I have by myself seen that something is wrong with my code and also my
> > brain.
> >
> > Could anyone be kind enough to tell me what to do....
> >
> > Where I am confused is how to test for other numbers without one and the
> > number itself. It turns out that all numbers pass the condition I set so
> > that would presuppose that all numbers are prime which is not.
> >
> > How exactly can I get it to run checks with other numbers such that it
> > doesn't include the number itself and 1.
> >
> > The code is as follows:
> >
> > for i in range(1,20):
> >
> >     if float(i) % 1 == 0 and float(i) % i == 0:
> >         print i, 'is a prime number'
>
> Your code only checks whether the number divides by 1 and itself. It
> should check the numbers in between, and if _any_ divides the number,
> decide it is not a prime number. This is best done in a separate
> function (note: I am writing it here for clarity of the underlying
> algorithm, there are various ways in which it could be made faster,
> shorter or more Pythonic):
>
> def isPrime(n):
>    divisorFound = False
>    for i in xrange(2, n):
>        if n % i == 0:
>            divisorFound = True
>    return not divisorFound     # divisorFound is true if and only if
> there is a number i (1<i<n) with n % i == 0
>
> for i in range(2,20):
>    if isPrime(i):
>         print i, 'is a prime number'
>
> By the way, do note that your cast to float is not a good idea. It
> probably won't hurt you in this case, but it definitely won't improve
> things. You'd much rather check exact equality with integers than with
> floats.
>
> --
> Andr? Engels, andreengels at gmail.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Nitin Pawar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100713/628ee47e/attachment.html>

From davea at ieee.org  Tue Jul 13 13:28:27 2010
From: davea at ieee.org (Dave Angel)
Date: Tue, 13 Jul 2010 07:28:27 -0400
Subject: [Tutor] Help
In-Reply-To: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
Message-ID: <4C3C4DDB.7080701@ieee.org>

Dipo Elegbede wrote:
> I was trying to write a code that prints prime numbers between 1 and 20.
>
> I have by myself seen that something is wrong with my code and also my
> brain.
>
> Could anyone be kind enough to tell me what to do....
>
> Where I am confused is how to test for other numbers without one and the
> number itself. It turns out that all numbers pass the condition I set so
> that would presuppose that all numbers are prime which is not.
>
> How exactly can I get it to run checks with other numbers such that it
> doesn't include the number itself and 1.
>
> The code is as follows:
>
> for i in range(1,20):
>
>     if float(i) % 1 == 0 and float(i) % i == 0:
>         print i, 'is a prime number'
>
>
>   
Break the problem down.  Instead of solving the "print all the primes 
from 1 to 20", first solve the "Is a given number prime".

then once you have a solution to that one, write a loop that calls it 20 
times, printing its conclusions.

So suppose you have the number 12.  How would you manually decide if 
it's prime?  You'd find the remainder for all the numbers between 2 and 
11, inclusive, and if *any* of those came out zero, you'd say it's not 
prime.

Write a function isprime() that expresses exactly that, returning False 
if any of the modulos came out zero, and True if they're all okay.  The 
function will have a loop, and inside the loop have a single if statement.

Test the function by calling it explicitly with various values.  Then 
when you're comfortable with that, solve the bigger problem as stated.

DaveA


From siren99 at yahoo.com  Tue Jul 13 14:40:44 2010
From: siren99 at yahoo.com (Siren Saren)
Date: Tue, 13 Jul 2010 05:40:44 -0700 (PDT)
Subject: [Tutor] Response to responses about list of lists: a meta exercise
	in mailinglist recursion
Message-ID: <768895.83808.qm@web44713.mail.sp1.yahoo.com>





I'm not sure if there's a way to submit responses 'live' or
whether it's better to respond to subthreads at once or together, so I'll err
on the side of discretion and just send one response.? Thanks to each of you who tried to help me.? I've responded individually below. 

 

To summarize the discussion so far:


I wondered if there was a decent way to sort a list that
contained two lists, where each could be distinguished based on the list's sequence and
the elements' data characteristics.? As a subsidiary
question, I wondered if there was a data structure I should aspire to put the
data into once I had it sorted.


In response to the first question: the consensus seems to be
that there is no good way to sort a non-alternating one-to-many list like this, so my strategy of deriving
the index numbers of every item, as awkward as it appears, may actually be the
best approach. 

 

In response to the second: a pickle, a dictionary, a
database, and a tuple with a sublist were all proposed.??? The choice seems somewhat arbitrary, but on
the bright side, I suppose that also confirms that I have a lot of flexibility
in what I choose.? 



Specific responses:


Steven,

I apologize for using 'reply,' I've never used a mailing
list before and didn't understand what would happen.? Is there some online forum where I could post
a message directly rather than mailing it in??
I see that other people are somehow responding to my message from the
more real-time updates I can get on activestate, but I don't know how they are
doing it since I haven't received the mailing yet that would include my message
and its responses.? 

If my list had a million books in it and 10 million page
numbers, would the approach I've outlined in my initial post be the best for
sorting them?? Like David and Eric you've
given me some good input on a data structure to use.? If I understand you right, you'd advocate
using a tuple of the books, bookmarks, where the bookmarks themselves are
sublists.? 


David, Yes, I agree it would?
be much better to store the data in a different manner.? The problem is that I'm not the creator of
the data.? Maybe you realize that and are
just suggesting the database structure rather than a dictionary or a pickle,
once I get my sorting accomplished?? If
the book example is confusing how about this.?
Say you discovered a bunch of data in a secret code document.? You know the sequence of the data relates the
elements to each other.? You also know
there are just two elements and that the sequence is a straightforward function
of say, integers to letters.? So the data
you've discovered looks like:


A 2 3 B 4 7 5 9 1 C 3 2 1 0 0 4 D 3 3 32 44 ...


Once I've sorted the data, I am curious how to best store it
(and why), and your answer does pertain to that-- use sql-- but I am also
curious if there's a less arcane approach than the one I'm using to try to do
the initial sorting.? Any thoughts, given
that I can't fix the way the data arrives??
Thanks for the database idea regardless.


Eric, I appreciate your input though I'm hard-pressed to
find its applicability.? It may be useful
as a way to store my data for this or any number of other programs though, and
that was a helpful article about the pickling process.? I don't know if pickle has any built-in
methods for relating data to other data.?
I'd imagine that if I were designing the data input process, rather than
just taking data that exists and trying to process it, I'd probably go with a
database for a situation like this.? Then
I'd have a more explicit system for referring each value to other values
through records, rather than having to infer them as I'm doing.? Regardless, I'm often in the same position of
trying to be helpful without knowing how, and I sincerely do appreciate the
attempt.? It creates a general atmosphere
of friendliness, which is so much better than being told I'm an idiot :)!


Lingering Questions: 

Anyone have a rationale for choosing
one of the data structures proposed??
Anyone have a better way to do the sorting than the process I outlined
in my first post (a. identify the elements. b. make a list of one of ?the element groups. c. get the index numbers
of that group in the broader list.? d.
list the other elements as indexes falling between the first group's indexes.? e. reorganize the data into a more logical
form)


Thanks again to everyone who responded!


Soren


      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100713/59e36836/attachment-0001.html>

From siren99 at yahoo.com  Tue Jul 13 14:54:27 2010
From: siren99 at yahoo.com (Siren Saren)
Date: Tue, 13 Jul 2010 05:54:27 -0700 (PDT)
Subject: [Tutor] Response to Alan re: list of lists response
In-Reply-To: <mailman.31.1279015204.9995.tutor@python.org>
Message-ID: <971118.96518.qm@web44702.mail.sp1.yahoo.com>

Alan,

Your message appeared on the forum right as I posted my response.? Brief unrelated thanks: your website has been a great help to me as I've been learning python.? I'm especially grateful to you for making it so easy to download in various formats, since my health problems make it hard for me to read at my desk and it was lovely to be able to put everything on my ebook-reader and work on it on the couch.? If anyone hasn't checked out Alan's website, which is more like a book, I highly recommend it.

The idea of making this into an object appeals to me very much, because I've been trying to get my head around creating objects as well as just using them.? Thank you, too, for the example code on how to think about creating such an object.? 

I'm positive now that my initial message was misleading, given that you also responded as though I could affect the way my data arrived.? Oddly,? I've already tried to develop a couple of 'programs' dealing with data in this form-- lists where the sequence means something but isn't merely alternation.? I assumed this must be a common problem but maybe programmers mostly deal with data that was made for their purposes nowadays.? It's interesting how self-referential the world becomes.

Thanks again for taking the time to both build your website and share your thoughts directly with me.? Means a lot



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100713/fd08039d/attachment.html>

From robert.johansson at math.umu.se  Tue Jul 13 14:52:46 2010
From: robert.johansson at math.umu.se (Robert Johansson)
Date: Tue, 13 Jul 2010 14:52:46 +0200
Subject: [Tutor] random graph
Message-ID: <000001cb228a$4b3a3c10$e1aeb430$@johansson@math.umu.se>

Dear all,

 

I'm trying to check the size of a component in a random graph with this code
(by a component I mean a maximal connected sub graph):

 

http://pastebin.com/SzC77HdU

 

I'm not 100 % sure that the code is working as it should but my question is
if there is a better way to design the whole thing. 

 

Basically I start with a empty graph (just a set of nodes represented as the
numbers between 0 and 10 ** 6) and generate random edges as pairs of
integers between 0 and 10 ** 6. Also I keep a dictionary (comps) matching
nodes to component numbers. If one of the nodes of the new edge doesn't
touch an existing component, I just add that node to the dictionary and give
it the same component number as the other node. If no node touches a
component the a new component number is generated and the new nodes are
added to the dict with that number. The problem is when an edge going
between two distinct components are encountered, say that edge (n, m) is
generated going between component i and j. Now I need to change all values
for keys in one of the components to the values of the other component so
that  they merge into a single component. The way I tried to do this is to
have lists of length one as values in the dict and by that (hopefully)
manage to update all values for a whole component just by changing a single
list item (I think of them as pointers to the same list).  

 

Will this work? Is there a better way to update the values of a component
(fast)?

 

/Robert

 

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100713/8b3d1116/attachment.html>

From jf_byrnes at comcast.net  Tue Jul 13 15:43:40 2010
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Tue, 13 Jul 2010 08:43:40 -0500
Subject: [Tutor] Path?
In-Reply-To: <201007120932.06800.steve@pearwood.info>
References: <4C3A0284.6090901@comcast.net>
	<201007120932.06800.steve@pearwood.info>
Message-ID: <4C3C6D8C.4090202@comcast.net>

Steven D'Aprano wrote:

My apologizes to Steven and the list, when I replied originally I messed 
up and sent it to him privately which was not my intention.


 > On Mon, 12 Jul 2010 03:42:28 am Jim Byrnes wrote:
 >> I am running Ubuntu.  I downloaded the source code examples for a
 >> book I purchased.  Some of the examples load image files located in
 >> the same directory as the program.  If I go to the current directory
 >> in the terminal the program can use the image files.  However, if I
 >> use a launcher or the filemanager it pops up an error dialog saying
 >> the file does not exist even though it is in the same directory.
 >>
 >> The program simply uses the files name.  Is there a way without
 >> editing the source and inserting the full path to run the program
 >> from a launcher or the filemanager and allow it to see files in the
 >> current directory?
 >
 > What file manager are you using? Nautilus? Konqueror? Something else?

Nautilus. I have it configured to run files with the extension .py when 
they are double clicked.

 > What do you mean, "use a launcher"? Use a launcher to do what? What sort
 > of launcher?

It runs programs and sits on the panel at the top of my Ubuntu desktop. 
  The command it uses is usr/bin/python2.6.  These are wxPython examples 
I am working with.

 > What pops up an error dialog? The launcher?

I am assuming Python. The title bar of the dialog says Python2 Error, 
the message is   Can't load image from file 'wxPython.jpg': file does 
not exist.

 > Which file does it claim doesn't exist? Python? The Python script? The
 > image file? What is the exact error message it gives?

See above.  The line that triggers the error is:  image = 
wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG)

 > There's probably a way to tell the launcher which working directory to
 > use, but of course that depends on the answers to the above questions.
 >

If I use the terminal to start the program it has no problem using the 
file.  There are multiple files in multiple directories so I was looking 
for a way to just double click them and have them run.  If it turns out 
that I must make changes to or for each of the files it will be easier 
to just keep using the terminal.  I've only been using Ubuntu for a few 
months so I was surprised that the program could not see a file that is 
in the same directory.

Regards,  Jim


From adam.jtm30 at gmail.com  Tue Jul 13 15:48:25 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Tue, 13 Jul 2010 14:48:25 +0100
Subject: [Tutor] Path?
In-Reply-To: <4C3C6D8C.4090202@comcast.net>
References: <4C3A0284.6090901@comcast.net>
	<201007120932.06800.steve@pearwood.info> 
	<4C3C6D8C.4090202@comcast.net>
Message-ID: <AANLkTikF2HzyOLTymwAjcWxr7KPiSNVuQyIhB07DtS_s@mail.gmail.com>

On 13 July 2010 14:43, Jim Byrnes <jf_byrnes at comcast.net> wrote:

> Steven D'Aprano wrote:
>
> My apologizes to Steven and the list, when I replied originally I messed up
> and sent it to him privately which was not my intention.
>
>
>
> > On Mon, 12 Jul 2010 03:42:28 am Jim Byrnes wrote:
> >> I am running Ubuntu.  I downloaded the source code examples for a
> >> book I purchased.  Some of the examples load image files located in
> >> the same directory as the program.  If I go to the current directory
> >> in the terminal the program can use the image files.  However, if I
> >> use a launcher or the filemanager it pops up an error dialog saying
> >> the file does not exist even though it is in the same directory.
> >>
> >> The program simply uses the files name.  Is there a way without
> >> editing the source and inserting the full path to run the program
> >> from a launcher or the filemanager and allow it to see files in the
> >> current directory?
> >
> > What file manager are you using? Nautilus? Konqueror? Something else?
>
> Nautilus. I have it configured to run files with the extension .py when
> they are double clicked.
>
>
> > What do you mean, "use a launcher"? Use a launcher to do what? What sort
> > of launcher?
>
> It runs programs and sits on the panel at the top of my Ubuntu desktop.
>  The command it uses is usr/bin/python2.6.  These are wxPython examples I am
> working with.
>
>
> > What pops up an error dialog? The launcher?
>
> I am assuming Python. The title bar of the dialog says Python2 Error, the
> message is   Can't load image from file 'wxPython.jpg': file does not exist.
>
>
> > Which file does it claim doesn't exist? Python? The Python script? The
> > image file? What is the exact error message it gives?
>
> See above.  The line that triggers the error is:  image =
> wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG)
>
>
> > There's probably a way to tell the launcher which working directory to
> > use, but of course that depends on the answers to the above questions.
> >
>
> If I use the terminal to start the program it has no problem using the
> file.  There are multiple files in multiple directories so I was looking for
> a way to just double click them and have them run.  If it turns out that I
> must make changes to or for each of the files it will be easier to just keep
> using the terminal.  I've only been using Ubuntu for a few months so I was
> surprised that the program could not see a file that is in the same
> directory.
>
> Regards,  Jim


The problem is ubuntu doesn't run the script from the directory it's in so
it's looking for wxPython.jpg somewhere else.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100713/cce96dc7/attachment-0001.html>

From stefan_ml at behnel.de  Tue Jul 13 16:41:56 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Tue, 13 Jul 2010 16:41:56 +0200
Subject: [Tutor] Response to responses about list of lists: a meta
 exercise in mailinglist recursion
In-Reply-To: <768895.83808.qm@web44713.mail.sp1.yahoo.com>
References: <768895.83808.qm@web44713.mail.sp1.yahoo.com>
Message-ID: <i1htvl$v9f$1@dough.gmane.org>

Siren Saren, 13.07.2010 14:40:
> I'm not sure if there's a way to submit responses 'live' or
> whether it's better to respond to subthreads at once or together, so I'll err
> on the side of discretion and just send one response.

It's not generally a problem to send one response like this regarding many 
posts, especially if you use it to summarise the previous discussion. But 
if you do, please take care to actually reply to one of the posts to make 
sure the mail clients and mailing list archives sort the message into the 
right thread. If you don't, you start a new thread (as you did here), which 
will be harder to find in archives.

Stefan


From emile at fenx.com  Tue Jul 13 17:51:55 2010
From: emile at fenx.com (Emile van Sebille)
Date: Tue, 13 Jul 2010 08:51:55 -0700
Subject: [Tutor] LOCATION ISSUES
In-Reply-To: <AANLkTimE0avkwqERd2wGI_YXvXbMAFlOytRFQU4dk9Z2@mail.gmail.com>
References: <AANLkTikmArXMy02yMv3st3-4QSqVc6HaVudrPNOUL3VP@mail.gmail.com>	<i1h12n$oon$1@dough.gmane.org>
	<AANLkTimE0avkwqERd2wGI_YXvXbMAFlOytRFQU4dk9Z2@mail.gmail.com>
Message-ID: <i1i25m$hjh$1@dough.gmane.org>

On 7/12/2010 11:52 PM Dipo Elegbede said...
>>
>> Which is what it will do when python is started from that directory.
>>
>> I actually found the copies that were made by the code in the same
>> directory but found out that they all had a .thumbnail ext which would not
>> open and it is understandable.
>>
>> I have however chaged that part of the code to carry .jpg hoping to let it
>> make thumbnails with jpg extensions.
>>
>>>
>>> How are you starting python?
>>>
>>
>> I am new to python.

:)  What I meant to ask was what are you typing in to actually start 
python and execute your code?  You need to open a command window, 
navigate to the directory where the images are stored, and start python 
from there so that glob will find the files.

HTH,

Emile


From bgailer at gmail.com  Tue Jul 13 18:10:32 2010
From: bgailer at gmail.com (bob gailer)
Date: Tue, 13 Jul 2010 12:10:32 -0400
Subject: [Tutor] Help
In-Reply-To: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
Message-ID: <4C3C8FF8.8040002@gmail.com>

You have gotten good advice from others.

My request is that you provide a meaningful subject when you post a 
question. We track by subject. "Help" is not the best subject.

Better would be "How to find prime numbers"

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From smokefloat at gmail.com  Tue Jul 13 19:20:37 2010
From: smokefloat at gmail.com (David Hutto)
Date: Tue, 13 Jul 2010 13:20:37 -0400
Subject: [Tutor] Response to responses about list of lists: a meta
	exercise in mailinglist recursion
In-Reply-To: <768895.83808.qm@web44713.mail.sp1.yahoo.com>
References: <768895.83808.qm@web44713.mail.sp1.yahoo.com>
Message-ID: <AANLkTindFWPyRv8fj3Ro6k0srrJxEKZoOIIVm2htcieP@mail.gmail.com>

On Tue, Jul 13, 2010 at 8:40 AM, Siren Saren <siren99 at yahoo.com> wrote:

> I'm not sure if there's a way to submit responses 'live' or whether it's
> better to respond to subthreads at once or together, so I'll err on the side
> of discretion and just send one response.  Thanks to each of you who tried
> to help me.  I've responded individually below.
>
>
>  To summarize the discussion so far:
>
>
> I wondered if there was a decent way to sort a list that contained two
> lists, where each could be distinguished based on the list's sequence and
> the elements' data characteristics.  As a subsidiary question, I wondered
> if there was a data structure I should aspire to put the data into once I
> had it sorted.
>
>
> In response to the first question: the consensus seems to be that there is
> no good way to sort a non-alternating one-to-many list like this, so my
> strategy of deriving the index numbers of every item, as awkward as it
> appears, may actually be the best approach.
>
>
>  In response to the second: a pickle, a dictionary, a database, and a
> tuple with a sublist were all proposed.    The choice seems somewhat
> arbitrary, but on the bright side, I suppose that also confirms that I have
> a lot of flexibility in what I choose.
>
>
> Specific responses:
>
>
> Steven,
>
> I apologize for using 'reply,' I've never used a mailing list before and
> didn't understand what would happen.  Is there some online forum where I
> could post a message directly rather than mailing it in?  I see that other
> people are somehow responding to my message from the more real-time updates
> I can get on activestate, but I don't know how they are doing it since I
> haven't received the mailing yet that would include my message and its
> responses.
>
> If my list had a million books in it and 10 million page numbers, would the
> approach I've outlined in my initial post be the best for sorting them?  Like
> David and Eric you've given me some good input on a data structure to use.
> If I understand you right, you'd advocate using a tuple of the books,
> bookmarks, where the bookmarks themselves are sublists.
>
>
> David, Yes, I agree it would  be much better to store the data in a
> different manner.  The problem is that I'm not the creator of the data.
>

This, again is a newbie statement but maybe importing re or regular
expressions to parse the known files would be helpful.

The way I'm thinking is that you put your books in a directory. Now, that
directory could contain directories of books with the individual text pages
within those book's directories, or something like a pdf.


Within these documents or directories, you search with an app for those
specific files. Now you can either list within the app those books and pages
and then search the directories, or you could search the directories first
and list the books, then specify the page you want to go to.

My DB idea would work if you placed in an ID, a page number, then a location
to the text file , or stored the text in the sqlite DB globfield .

> Maybe you realize that and are just suggesting the database structure
> rather than a dictionary or a pickle, once I get my sorting accomplished?
> If the book example is confusing how about this.  Say you discovered a
> bunch of data in a secret code document.  You know the sequence of the
> data relates the elements to each other.  You also know there are just two
> elements and that the sequence is a straightforward function of say,
> integers to letters.  So the data you've discovered looks like:
>
>
> A 2 3 B 4 7 5 9 1 C 3 2 1 0 0 4 D 3 3 32 44 ...
>
>
> Once I've sorted the data, I am curious how to best store it (and why), and
> your answer does pertain to that-- use sql--
>

Not just sql, but maybe, and dicts/lists are not my specialty yet, but
utilize it in the process. The main objective of utilizing the DB, in MHO,
is that it forces you to state the information you want to use, so this
refines your code, by defining the fields you must use to state and store
the data. So you have a book, and a page, and a author, and an id to match
these with.

Now you could use an app to search the 'book' directory, and then  'for each
in' print the book containing folder's name., then open() the page and could
go further to bring up the exact line/paragraph of the individual page.

> but I am also curious if there's a less arcane approach than the one I'm
> using to try to do the initial sorting.  Any thoughts, given that I can't
> fix the way the data arrives?  Thanks for the database idea regardless.
>
>
>
This again would be regular expressions, as far as I'm thinking, import re,
help(re) or dir(re), or pydoc re, or something like that. You parse the
book's file or directory, and look for the tags to read out the book's name,
author or page, and then you can just select the book, type in the page
number, or select from a predetermined list of pages that have explanations
as to why you should visit the page, or read the text.


> Eric, I appreciate your input though I'm hard-pressed to find its
> applicability.  It may be useful as a way to store my data for this or any
> number of other programs though, and that was a helpful article about the
> pickling process.  I don't know if pickle has any built-in methods for
> relating data to other data.  I'd imagine that if I were designing the
> data input process, rather than just taking data that exists and trying to
> process it, I'd probably go with a database for a situation like this.  Then
> I'd have a more explicit system for referring each value to other values
> through records, rather than having to infer them as I'm doing.  Regardless,
> I'm often in the same position of trying to be helpful without knowing how,
> and I sincerely do appreciate the attempt.  It creates a general
> atmosphere of friendliness, which is so much better than being told I'm an
> idiot :)!
>
>
> Lingering Questions:
>
>
> Anyone have a rationale for choosing one of the data structures proposed?
> Anyone have a better way to do the sorting than the process I outlined in
> my first post (a. identify the elements. b. make a list of one of  the
> element groups. c. get the index numbers of that group in the broader list.
> d. list the other elements as indexes falling between the first group's
> indexes.  e. reorganize the data into a more logical form)
>
>
> Thanks again to everyone who responded!
>
>
> Soren
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100713/3de3c633/attachment-0001.html>

From smokefloat at gmail.com  Tue Jul 13 20:02:53 2010
From: smokefloat at gmail.com (David Hutto)
Date: Tue, 13 Jul 2010 14:02:53 -0400
Subject: [Tutor] Response to responses about list of lists: a meta
	exercise in mailinglist recursion
In-Reply-To: <AANLkTindFWPyRv8fj3Ro6k0srrJxEKZoOIIVm2htcieP@mail.gmail.com>
References: <768895.83808.qm@web44713.mail.sp1.yahoo.com>
	<AANLkTindFWPyRv8fj3Ro6k0srrJxEKZoOIIVm2htcieP@mail.gmail.com>
Message-ID: <AANLkTilEzfNgaJi1gg_gVkH5PhNIF4kB-ci2KystH51J@mail.gmail.com>

On Tue, Jul 13, 2010 at 1:20 PM, David Hutto <smokefloat at gmail.com> wrote:

>
>
> On Tue, Jul 13, 2010 at 8:40 AM, Siren Saren <siren99 at yahoo.com> wrote:
>
>>  I'm not sure if there's a way to submit responses 'live' or whether it's
>> better to respond to subthreads at once or together, so I'll err on the side
>> of discretion and just send one response.  Thanks to each of you who
>> tried to help me.  I've responded individually below.
>>
>>
>>  To summarize the discussion so far:
>>
>>
>> I wondered if there was a decent way to sort a list that contained two
>> lists, where each could be distinguished based on the list's sequence and
>> the elements' data characteristics.  As a subsidiary question, I wondered
>> if there was a data structure I should aspire to put the data into once I
>> had it sorted.
>>
>>
>> In response to the first question: the consensus seems to be that there is
>> no good way to sort a non-alternating one-to-many list like this, so my
>> strategy of deriving the index numbers of every item, as awkward as it
>> appears, may actually be the best approach.
>>
>>
>>  In response to the second: a pickle, a dictionary, a database, and a
>> tuple with a sublist were all proposed.    The choice seems somewhat
>> arbitrary, but on the bright side, I suppose that also confirms that I have
>> a lot of flexibility in what I choose.
>>
>>
>> Specific responses:
>>
>>
>> Steven,
>>
>> I apologize for using 'reply,' I've never used a mailing list before and
>> didn't understand what would happen.  Is there some online forum where I
>> could post a message directly rather than mailing it in?  I see that
>> other people are somehow responding to my message from the more real-time
>> updates I can get on activestate, but I don't know how they are doing it
>> since I haven't received the mailing yet that would include my message and
>> its responses.
>>
>> If my list had a million books in it and 10 million page numbers, would
>> the approach I've outlined in my initial post be the best for sorting them?
>> Like David and Eric you've given me some good input on a data structure to
>> use.  If I understand you right, you'd advocate using a tuple of the
>> books, bookmarks, where the bookmarks themselves are sublists.
>>
>>
>> David, Yes, I agree it would  be much better to store the data in a
>> different manner.  The problem is that I'm not the creator of the data.
>>
>
> This, again is a newbie statement but maybe importing re or regular
> expressions to parse the known files would be helpful.
>
> The way I'm thinking is that you put your books in a directory. Now, that
> directory could contain directories of books with the individual text pages
> within those book's directories, or something like a pdf.
>
>
> Within these documents or directories, you search with an app for those
> specific files. Now you can either list within the app those books and pages
> and then search the directories, or you could search the directories first
> and list the books, then specify the page you want to go to.
>
> My DB idea would work if you placed in an ID, a page number, then a
> location to the text file , or stored the text in the sqlite DB globfield .
>
>>  Maybe you realize that and are just suggesting the database structure
>> rather than a dictionary or a pickle, once I get my sorting accomplished?
>> If the book example is confusing how about this.  Say you discovered a
>> bunch of data in a secret code document.  You know the sequence of the
>> data relates the elements to each other.  You also know there are just
>> two elements and that the sequence is a straightforward function of say,
>> integers to letters.  So the data you've discovered looks like:
>>
>>
>> A 2 3 B 4 7 5 9 1 C 3 2 1 0 0 4 D 3 3 32 44 ...
>>
>>
>> Once I've sorted the data, I am curious how to best store it (and why),
>> and your answer does pertain to that-- use sql--
>>
>
> Not just sql, but maybe, and dicts/lists are not my specialty yet, but
> utilize it in the process. The main objective of utilizing the DB, in MHO,
> is that it forces you to state the information you want to use, so this
> refines your code, by defining the fields you must use to state and store
> the data. So you have a book, and a page, and a author, and an id to match
> these with.
>
> Now you could use an app to search the 'book' directory, and then  'for
> each in' print the book containing folder's name., then open() the page and
> could go further to bring up the exact line/paragraph of the individual
> page.
>
>> but I am also curious if there's a less arcane approach than the one I'm
>> using to try to do the initial sorting.  Any thoughts, given that I can't
>> fix the way the data arrives?  Thanks for the database idea regardless.
>>
>>
>>
> This again would be regular expressions, as far as I'm thinking, import re,
> help(re) or dir(re), or pydoc re, or something like that. You parse the
> book's file or directory, and look for the tags to read out the book's name,
> author or page, and then you can just select the book, type in the page
> number, or select from a predetermined list of pages that have explanations
> as to why you should visit the page, or read the text.
>
>
>> Eric, I appreciate your input though I'm hard-pressed to find its
>> applicability.  It may be useful as a way to store my data for this or
>> any number of other programs though, and that was a helpful article about
>> the pickling process.  I don't know if pickle has any built-in methods
>> for relating data to other data.  I'd imagine that if I were designing
>> the data input process, rather than just taking data that exists and trying
>> to process it, I'd probably go with a database for a situation like this.
>> Then I'd have a more explicit system for referring each value to other
>> values through records, rather than having to infer them as I'm doing.  Regardless,
>> I'm often in the same position of trying to be helpful without knowing how,
>> and I sincerely do appreciate the attempt.  It creates a general
>> atmosphere of friendliness, which is so much better than being told I'm an
>> idiot :)!
>>
>>
>> Lingering Questions:
>>
>>
>> Anyone have a rationale for choosing one of the data structures proposed?
>> Anyone have a better way to do the sorting than the process I outlined in
>> my first post (a. identify the elements. b. make a list of one of  the
>> element groups. c. get the index numbers of that group in the broader list.
>> d. list the other elements as indexes falling between the first group's
>> indexes.  e. reorganize the data into a more logical form)
>>
>>
>> Thanks again to everyone who responded!
>>
>>
>> Soren
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
First,  would be, where is the data you're not able to have control over,
coming from? What format is it in? How do you want to access it, and how do
you want to display it?

Answer the simplest first, and the details follow..
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100713/29975bc4/attachment.html>

From alan.gauld at btinternet.com  Tue Jul 13 21:15:16 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 13 Jul 2010 20:15:16 +0100
Subject: [Tutor] Response to Alan re: list of lists response
References: <mailman.31.1279015204.9995.tutor@python.org>
	<971118.96518.qm@web44702.mail.sp1.yahoo.com>
Message-ID: <i1ie01$v7r$1@dough.gmane.org>


"Siren Saren" <siren99 at yahoo.com> wrote
> unrelated thanks: your website has been a great help

Thanks for the kind words :-)

> The idea of making this into an object appeals to me
> very much, because I've been trying to get my head around
> creating objects as well as just using them.

It has some advantages since it is possible to write functions
that are used when sorting so you can sort complex data sets
relatively easily at the macro scale of using the objects. The
comparison functions useed to sort may of course be arbitrarily
complex - but at least the higher level application code is kept
simple..

> I'm positive now that my initial message was misleading,
> given that you also responded as though I could affect
> the way my data arrived.

You gave no clue whatsoever how the data arrived.
Is it in a file? a data stream? a database?
The first thing to do in any data processing application is to read
the data into the data format that you want it to be in to do the
processing.

> Oddly, I've already tried to develop a couple of 'programs' dealing
> with data in this form-- lists where the sequence means something
> but isn't merely alternation.

I'm still not sure I understand what you mean by that. Your book/pages
and crypto examples seemed straighforward but you didn't give any
examples of what the sorted v unsorted data would look like.

> I assumed this must be a common problem but maybe
> programmers mostly deal with data that was made for their
> purposes nowadays.

Not at all but the first thing you do in any data processing problem
is take the input data and store it how you want it, not how it 
arrives!
But how you want it will depend on what you are trying to do with it!
That's why the many responses vary - it depends on how you want
to manipulate it.

HTH,


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



From jf_byrnes at comcast.net  Wed Jul 14 00:27:32 2010
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Tue, 13 Jul 2010 17:27:32 -0500
Subject: [Tutor] Path?
In-Reply-To: <AANLkTikF2HzyOLTymwAjcWxr7KPiSNVuQyIhB07DtS_s@mail.gmail.com>
References: <4C3A0284.6090901@comcast.net>
	<201007120932.06800.steve@pearwood.info>
	<4C3C6D8C.4090202@comcast.net>
	<AANLkTikF2HzyOLTymwAjcWxr7KPiSNVuQyIhB07DtS_s@mail.gmail.com>
Message-ID: <4C3CE854.5060803@comcast.net>

Adam Bark wrote:
> On 13 July 2010 14:43, Jim Byrnes<jf_byrnes at comcast.net>  wrote:
>
>> Steven D'Aprano wrote:
>>
>> My apologizes to Steven and the list, when I replied originally I messed up
>> and sent it to him privately which was not my intention.
>>
>>
>>
>>> On Mon, 12 Jul 2010 03:42:28 am Jim Byrnes wrote:
>>>> I am running Ubuntu.  I downloaded the source code examples for a
>>>> book I purchased.  Some of the examples load image files located in
>>>> the same directory as the program.  If I go to the current directory
>>>> in the terminal the program can use the image files.  However, if I
>>>> use a launcher or the filemanager it pops up an error dialog saying
>>>> the file does not exist even though it is in the same directory.
>>>>
>>>> The program simply uses the files name.  Is there a way without
>>>> editing the source and inserting the full path to run the program
>>>> from a launcher or the filemanager and allow it to see files in the
>>>> current directory?
>>>
>>> What file manager are you using? Nautilus? Konqueror? Something else?
>>
>> Nautilus. I have it configured to run files with the extension .py when
>> they are double clicked.
>>
>>
>>> What do you mean, "use a launcher"? Use a launcher to do what? What sort
>>> of launcher?
>>
>> It runs programs and sits on the panel at the top of my Ubuntu desktop.
>>   The command it uses is usr/bin/python2.6.  These are wxPython examples I am
>> working with.
>>
>>
>>> What pops up an error dialog? The launcher?
>>
>> I am assuming Python. The title bar of the dialog says Python2 Error, the
>> message is   Can't load image from file 'wxPython.jpg': file does not exist.
>>
>>
>>> Which file does it claim doesn't exist? Python? The Python script? The
>>> image file? What is the exact error message it gives?
>>
>> See above.  The line that triggers the error is:  image =
>> wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG)
>>
>>
>>> There's probably a way to tell the launcher which working directory to
>>> use, but of course that depends on the answers to the above questions.
>>>
>>
>> If I use the terminal to start the program it has no problem using the
>> file.  There are multiple files in multiple directories so I was looking for
>> a way to just double click them and have them run.  If it turns out that I
>> must make changes to or for each of the files it will be easier to just keep
>> using the terminal.  I've only been using Ubuntu for a few months so I was
>> surprised that the program could not see a file that is in the same
>> directory.
>>
>> Regards,  Jim
>
>
> The problem is ubuntu doesn't run the script from the directory it's in so
> it's looking for wxPython.jpg somewhere else.
>

OK, I mistakenly thought that double-clicking on file in Nautilus would 
take care of the path info.

In my reply above I also mentioned that I tried by dropping it on a 
Launcher on the top panel and that the command the launcher uses is 
usr/bin/python2.6.  Is there a way that the command can be changed so 
that it will look in the same directory the python script is in for any 
file it needs?

Thanks,  Jim

From adam.jtm30 at gmail.com  Wed Jul 14 00:49:38 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Tue, 13 Jul 2010 23:49:38 +0100
Subject: [Tutor] Path?
In-Reply-To: <4C3CE854.5060803@comcast.net>
References: <4C3A0284.6090901@comcast.net>
	<201007120932.06800.steve@pearwood.info> 
	<4C3C6D8C.4090202@comcast.net>
	<AANLkTikF2HzyOLTymwAjcWxr7KPiSNVuQyIhB07DtS_s@mail.gmail.com> 
	<4C3CE854.5060803@comcast.net>
Message-ID: <AANLkTik6FcbxVzajVr5HDOrG3j5EaJbRk8Uv7SnbQT6k@mail.gmail.com>

On 13 July 2010 23:27, Jim Byrnes <jf_byrnes at comcast.net> wrote:

> Adam Bark wrote:
>
>> On 13 July 2010 14:43, Jim Byrnes<jf_byrnes at comcast.net>  wrote:
>>
>>  Steven D'Aprano wrote:
>>>
>>> My apologizes to Steven and the list, when I replied originally I messed
>>> up
>>> and sent it to him privately which was not my intention.
>>>
>>>
>>>
>>>  On Mon, 12 Jul 2010 03:42:28 am Jim Byrnes wrote:
>>>>
>>>>> I am running Ubuntu.  I downloaded the source code examples for a
>>>>> book I purchased.  Some of the examples load image files located in
>>>>> the same directory as the program.  If I go to the current directory
>>>>> in the terminal the program can use the image files.  However, if I
>>>>> use a launcher or the filemanager it pops up an error dialog saying
>>>>> the file does not exist even though it is in the same directory.
>>>>>
>>>>> The program simply uses the files name.  Is there a way without
>>>>> editing the source and inserting the full path to run the program
>>>>> from a launcher or the filemanager and allow it to see files in the
>>>>> current directory?
>>>>>
>>>>
>>>> What file manager are you using? Nautilus? Konqueror? Something else?
>>>>
>>>
>>> Nautilus. I have it configured to run files with the extension .py when
>>> they are double clicked.
>>>
>>>
>>>  What do you mean, "use a launcher"? Use a launcher to do what? What sort
>>>> of launcher?
>>>>
>>>
>>> It runs programs and sits on the panel at the top of my Ubuntu desktop.
>>>  The command it uses is usr/bin/python2.6.  These are wxPython examples I
>>> am
>>> working with.
>>>
>>>
>>>  What pops up an error dialog? The launcher?
>>>>
>>>
>>> I am assuming Python. The title bar of the dialog says Python2 Error, the
>>> message is   Can't load image from file 'wxPython.jpg': file does not
>>> exist.
>>>
>>>
>>>  Which file does it claim doesn't exist? Python? The Python script? The
>>>> image file? What is the exact error message it gives?
>>>>
>>>
>>> See above.  The line that triggers the error is:  image =
>>> wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG)
>>>
>>>
>>>  There's probably a way to tell the launcher which working directory to
>>>> use, but of course that depends on the answers to the above questions.
>>>>
>>>>
>>> If I use the terminal to start the program it has no problem using the
>>> file.  There are multiple files in multiple directories so I was looking
>>> for
>>> a way to just double click them and have them run.  If it turns out that
>>> I
>>> must make changes to or for each of the files it will be easier to just
>>> keep
>>> using the terminal.  I've only been using Ubuntu for a few months so I
>>> was
>>> surprised that the program could not see a file that is in the same
>>> directory.
>>>
>>> Regards,  Jim
>>>
>>
>>
>> The problem is ubuntu doesn't run the script from the directory it's in so
>> it's looking for wxPython.jpg somewhere else.
>>
>>
> OK, I mistakenly thought that double-clicking on file in Nautilus would
> take care of the path info.
>
> In my reply above I also mentioned that I tried by dropping it on a
> Launcher on the top panel and that the command the launcher uses is
> usr/bin/python2.6.  Is there a way that the command can be changed so that
> it will look in the same directory the python script is in for any file it
> needs?
>
> Thanks,  Jim


Not sure if you got my previous email but you could try writing the bash
script I posted (with the $1 line to get the path) and setting that as your
launcher, I think it should work.

Let me know if you didn't get it or it doesn't work.

HTH,
Adam.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100713/c49b20ae/attachment.html>

From steve at pearwood.info  Wed Jul 14 02:19:34 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 14 Jul 2010 10:19:34 +1000
Subject: [Tutor] Response to responses about list of lists: a meta
	exercise in mailinglist recursion
In-Reply-To: <768895.83808.qm@web44713.mail.sp1.yahoo.com>
References: <768895.83808.qm@web44713.mail.sp1.yahoo.com>
Message-ID: <201007141019.34529.steve@pearwood.info>

On Tue, 13 Jul 2010 10:40:44 pm Siren Saren wrote:
> I'm not sure if there's a way to submit responses 'live' or
> whether it's better to respond to subthreads at once or together, so
> I'll err on the side of discretion and just send one response.?

Generally it's better, or at least more common, to respond to each 
response individually. But that's generally because people on mailing 
lists receive individual pieces of mail instead of a single giant 
digest containing the entire day's email traffic.


> In response to the first question: the consensus seems to be
> that there is no good way to sort a non-alternating one-to-many list
> like this, so my strategy of deriving the index numbers of every
> item, as awkward as it appears, may actually be the best approach.

No, a better approach is to split the list into separate lists:

mixedlist = [
 'Crime and punishment', 10, 40, 30, 
 "Brother's Karamazov", 22, 55, 9000, 
 "Father's and Sons", 100,
 'Anna Karenina', 1, 2, 4, 7, 9,
]

# untested
current_book = None
current_pages = []
result = []
for item in mixedlist:
    # Is it a title, or an integer page?
    if isinstance(item, str):
        # It's a title.
        if current_book is not None:
            result.append( (current_book, current_pages) )
        current_book = item
        current_pages = []
    else:
        # It's a page number.
        current_pages.append(item)

This will split the mixed list of titles, page numbers into a 
consolidated list of (title, list-of-page-numbers) like this:

booklist = [
?("Crime and punishment", [10, 40, 30]),
?("Brother's Karamazov", [22, 55, 9000]),
?("Father's and Sons", [100]),
?("Anna Karenina", [1, 2, 4, 7, 9]),
]

It's easy to adapt it to use a dictionary instead of a list. Change 
result to an empty dict {} instead of an empty list [], and change the 
line:

result.append( (current_book, current_pages) )

into:

result[current_book] = current_pages



One other thing... it's possible that your data is provided to you in 
text form, so that you have a single string like:

"Crime and punishment, page 10, page 40, page 30, ..."

instead of the more useful list of titles and integers. Some people have 
suggested using regular expressions to process the page numbers. That's 
fine, but it's rather overkill, like using a bulldozer to move a 
shovelful of dirt. Here's an (untested) filter to convert the one long 
string into a list of titles and integer pages:

result = []
for item in long_string.split(','):
    item = item.strip()  # get rid of leading and trailing spaces
    if item.startswith('page '):
        item = int(item[5:])
    result.append(item)

This assumes the data is well-formed, there are no typos such as "pgae 
15" in the data, and most importantly, no commas in the book titles.

This can be written as a two-liner, at the cost of some readability:

items = [item.strip() for item in long_string.split(',')]
result = [int(s[5:]) if s.startswith('page ') else s for s in items]

Making it into a one-liner is left as an exercise for the masochistic.


This demonstrates the basic principle of data processing of this kind. 
You start with a bunch of data in one form, and you transform it into 
another, slightly different and more useful form, using a series on 
individual filters or transformation functions:

Start with one long string.
Divide it into a list of substrings.
Transform it into a list of strings and integers.
Collate the integers with the string they belong to.
Do something useful with the pairs of (string, list-of-integers)


[...]
> I apologize for using 'reply,' I've never used a mailing
> list before and didn't understand what would happen.

Using rely is fine, but trim your response! Think of it like this. 
Suppose you received dozens of letters each day, from many different 
people, but the post office consolidated it all into a single envelope 
and delivered it once a day (a "digest"). If you wanted to reply to 
something from Fred, you wouldn't photocopy the entire day's collection 
of mail, all two hundred letters, and stick it at the bottom of your 
reply, would you? Well, that's what your mail program does, by default. 
It only takes a second to delete that excess baggage from your reply 
before hitting send.



> Is there some 
> online forum where I could post a message directly rather than
> mailing it in?

I don't think there's an online forum, because this is an email mailing 
list, not a web forum.

If you're starting a new discussion, or raising a new question, make a 
fresh, blank email, put a descriptive title in the subject line, and 
put tutor at python.org as the To address. 

If you're replying to an existing message, using reply is fine, but just 
trim the quoted text. You have a delete key -- learn how to use it :)


> I see that other people are somehow responding to my message from the
> more real-time updates I can get on activestate, but I don't know how
> they are doing it since I haven't received the mailing yet that would
> include my message and its responses.

That's because they'll be subscribed directly to the tutor mailing list, 
and getting individual pieces of mail as they're sent rather than a 
queued up and consolidated digest.


> If my list had a million books in it and 10 million page
> numbers, would the approach I've outlined in my initial post be the
> best for sorting them??

Ten million items isn't much for modern computers with gigabytes of 
memory. It's *approaching* "much", but hasn't quite reached it yet, and 
for most applications, it doesn't matter if it takes 2 seconds to 
pre-process your data instead of 0.5 second, so long as that's a 
one-off cost. If you have to do it again and again, that's another 
thing!




-- 
Steven D'Aprano

From jf_byrnes at comcast.net  Wed Jul 14 03:53:08 2010
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Tue, 13 Jul 2010 20:53:08 -0500
Subject: [Tutor] Path?
In-Reply-To: <AANLkTik6FcbxVzajVr5HDOrG3j5EaJbRk8Uv7SnbQT6k@mail.gmail.com>
References: <4C3A0284.6090901@comcast.net>
	<201007120932.06800.steve@pearwood.info>
	<4C3C6D8C.4090202@comcast.net>
	<AANLkTikF2HzyOLTymwAjcWxr7KPiSNVuQyIhB07DtS_s@mail.gmail.com>
	<4C3CE854.5060803@comcast.net>
	<AANLkTik6FcbxVzajVr5HDOrG3j5EaJbRk8Uv7SnbQT6k@mail.gmail.com>
Message-ID: <4C3D1884.8070501@comcast.net>

Adam Bark wrote:

<snipped some old stuff>

>>>> If I use the terminal to start the program it has no problem using the
>>>> file.  There are multiple files in multiple directories so I was looking
>>>> for
>>>> a way to just double click them and have them run.  If it turns out that
>>>> I
>>>> must make changes to or for each of the files it will be easier to just
>>>> keep
>>>> using the terminal.  I've only been using Ubuntu for a few months so I
>>>> was
>>>> surprised that the program could not see a file that is in the same
>>>> directory.
>>>>
>>>> Regards,  Jim
>>>>
>>>
>>>
>>> The problem is ubuntu doesn't run the script from the directory it's in so
>>> it's looking for wxPython.jpg somewhere else.
>>>
>>>
>> OK, I mistakenly thought that double-clicking on file in Nautilus would
>> take care of the path info.
>>
>> In my reply above I also mentioned that I tried by dropping it on a
>> Launcher on the top panel and that the command the launcher uses is
>> usr/bin/python2.6.  Is there a way that the command can be changed so that
>> it will look in the same directory the python script is in for any file it
>> needs?
>>
>> Thanks,  Jim
>
>
> Not sure if you got my previous email but you could try writing the bash
> script I posted (with the $1 line to get the path) and setting that as your
> launcher, I think it should work.
>
> Let me know if you didn't get it or it doesn't work.
>
> HTH,
> Adam.
>

I got it, got sidetracked and then forgot to look at it again.  Thanks 
for reminding me.  Your idea works, but with one little downside.  The 
directories I am working with are chapters in a book.  So as I move from 
chapter to chapter I will need to change the bash script, but this seems 
to be less typing than using the terminal.

Thanks,  Jim

From bgailer at gmail.com  Wed Jul 14 03:58:01 2010
From: bgailer at gmail.com (bob gailer)
Date: Tue, 13 Jul 2010 21:58:01 -0400
Subject: [Tutor] Help
In-Reply-To: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
Message-ID: <4C3D19A9.7090008@gmail.com>

On 7/13/2010 5:50 AM, Dipo Elegbede wrote:
> I was trying to write a code that prints prime numbers between 1 and 20.

Other suggestions
  - you need only test divisors up to the square root of the candidate.
- you can easily eliminate all even numbers and numbers divisible by 3.

for i in range(0,7,3):
   isPrime(i-1)
   isPrime(i+1)

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From anand.shashwat at gmail.com  Wed Jul 14 04:38:54 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Wed, 14 Jul 2010 08:08:54 +0530
Subject: [Tutor] Help
In-Reply-To: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
Message-ID: <AANLkTimk9DtHlyhU7z4WbNoJDaeW3FK3ErFuu1fHtjir@mail.gmail.com>

On Tue, Jul 13, 2010 at 3:20 PM, Dipo Elegbede <delegbede at dudupay.com>wrote:

> I was trying to write a code that prints prime numbers between 1 and 20.
>
> I have by myself seen that something is wrong with my code and also my
> brain.
>
> Could anyone be kind enough to tell me what to do....
>
> Where I am confused is how to test for other numbers without one and the
> number itself. It turns out that all numbers pass the condition I set so
> that would presuppose that all numbers are prime which is not.
>
> How exactly can I get it to run checks with other numbers such that it
> doesn't include the number itself and 1.
>
> The code is as follows:
>
> for i in range(1,20):
>
>     if float(i) % 1 == 0 and float(i) % i == 0:
>         print i, 'is a prime number'
>

Do you realize that all the numbers are divisible by 1. Hence float(i) % 1
_will be always zero_.
Now again, Do you realize that every number is divisible by itself. So
float(i) % i will also always be zero.
Also are you using float when dealing with integers.
Steps:
* You should probably check whether a number is prime.
* Then you should add extra loop to check whether in a given range of
numbers how many are prime.
* Now you optimize the code for lesse number of calculations, say for n
check for divisibility only until sqrt(n)
* Now you read wiki, read about sieve and apply sieve of erastothenes, to
make the code fast.
* Again memoize your code, so that it becomes more fast.
With all this done, you have a pretty handy code with yourself, coded by
you.
* Now solve this problem - https://www.spoj.pl/problems/PRIME1/ , which
can't be solved unless your code is highly optimized.
* If you have more curiosity, look for sieve of atkin.

Finish these and you are well off with primes :)

~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/97c7eccc/attachment.html>

From memilanuk at gmail.com  Wed Jul 14 06:31:44 2010
From: memilanuk at gmail.com (Monte Milanuk)
Date: Tue, 13 Jul 2010 21:31:44 -0700
Subject: [Tutor] Handling 'None' (null) values when processing sqlite cursor
	results
Message-ID: <i1jeji$rho$1@dough.gmane.org>

Hello all,

I'm struggling a bit trying to find the right way to deal with null 
values in my sqlite database when querying it and processing the results 
in python.

If my cursor.fetchall() results return the following:

(104, None, u'Sylvester', None, u'Evans', None, u'527-9210 Proin Av.', 
u'Liberal', u'VT', u'24742', u'1-135-197-1139', 
u'vehicula.Pellentesque at idmollis.edu', u'2010-07-13 22:52:50', 
u'2010-07-13 22:52:50')

At first I was having fits as str.join() was giving me a 'NoneType 
error'.  I found one way around that, by processing the results so the 
'None' values got omitted from the list by the time they got to str.join().

I thought that was the end of that, until I tried working with the 
returned records in another fashion and found that having the 'None' 
values omitted really messed with the list order which I was depending 
on i.e. list[5] could be different fields depending on how many 'None' 
values had been omitted.  And if I didn't omit them, when I printed out 
the user name in the format 'first''middle''last' from the above record, 
I got 'Sylvester''None''Evans' rather than just 'Sylvester''Evans' (i.e. 
with no middle initial).

So... I guess my question is, is there a good/proper way to handle the 
'None' values as returned by sqlite from a table that may have some null 
values in individual records?  Basically I want not have the None/Null 
values show up but to keep them as place holders to make sure i get the 
values in the right spots...

TIA,

Monte


From andreengels at gmail.com  Wed Jul 14 09:03:52 2010
From: andreengels at gmail.com (Andre Engels)
Date: Wed, 14 Jul 2010 09:03:52 +0200
Subject: [Tutor] Handling 'None' (null) values when processing sqlite
	cursor results
In-Reply-To: <i1jeji$rho$1@dough.gmane.org>
References: <i1jeji$rho$1@dough.gmane.org>
Message-ID: <AANLkTimGhahY5cuhW7U-Tyztf4UCldmDVtUKvNAfDHIh@mail.gmail.com>

On Wed, Jul 14, 2010 at 6:31 AM, Monte Milanuk <memilanuk at gmail.com> wrote:
> Hello all,
>
> I'm struggling a bit trying to find the right way to deal with null values
> in my sqlite database when querying it and processing the results in python.
>
> If my cursor.fetchall() results return the following:
>
> (104, None, u'Sylvester', None, u'Evans', None, u'527-9210 Proin Av.',
> u'Liberal', u'VT', u'24742', u'1-135-197-1139',
> u'vehicula.Pellentesque at idmollis.edu', u'2010-07-13 22:52:50', u'2010-07-13
> 22:52:50')
>
> At first I was having fits as str.join() was giving me a 'NoneType error'.
> ?I found one way around that, by processing the results so the 'None' values
> got omitted from the list by the time they got to str.join().
>
> I thought that was the end of that, until I tried working with the returned
> records in another fashion and found that having the 'None' values omitted
> really messed with the list order which I was depending on i.e. list[5]
> could be different fields depending on how many 'None' values had been
> omitted. ?And if I didn't omit them, when I printed out the user name in the
> format 'first''middle''last' from the above record, I got
> 'Sylvester''None''Evans' rather than just 'Sylvester''Evans' (i.e. with no
> middle initial).
>
> So... I guess my question is, is there a good/proper way to handle the
> 'None' values as returned by sqlite from a table that may have some null
> values in individual records? ?Basically I want not have the None/Null
> values show up but to keep them as place holders to make sure i get the
> values in the right spots...

It depends a bit on what you want to do with the values. My preference
would be to keep the result of cursor.fetchall(), and instead
re-define the output function(s) that I use (so don't use
str.join(record), but some myjoin(str,record) that I defined). Or,
even better, to define a class for these, create an object of the
class from the fetchall result, and have things like the myjoin before
as class methods or properties.

-- 
Andr? Engels, andreengels at gmail.com

From andreengels at gmail.com  Wed Jul 14 09:11:45 2010
From: andreengels at gmail.com (Andre Engels)
Date: Wed, 14 Jul 2010 09:11:45 +0200
Subject: [Tutor] Help
In-Reply-To: <AANLkTik0h0FdtyvS9HDvc861muXF6iqmZEIJQEq0RlRx@mail.gmail.com>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com> 
	<AANLkTilRgj1K6UXXc_LIfhM7UZWKk_QOkoFXwklgiw7w@mail.gmail.com> 
	<AANLkTik0h0FdtyvS9HDvc861muXF6iqmZEIJQEq0RlRx@mail.gmail.com>
Message-ID: <AANLkTimJt0iCXJv-aRTzNkqWL-lwD8KhJVOHUjTAckf4@mail.gmail.com>

On Tue, Jul 13, 2010 at 12:34 PM, Nitin Pawar <nitinpawar432 at gmail.com> wrote:
> Adding to what Andre said,
> another way of optimizing the problem would be
> storing the prime number in the range you want to check an array and see if
> the given number is divisible by any of those prime number

As I wrote, my code was not optimalized for either code size or
execution time. Other obvious speed-ups, apart from the one you
mention, are to only search up to the square root of the number
(rather than to the number minus 1), and to immediately break out of
the loop once a divisor has been found.


-- 
Andr? Engels, andreengels at gmail.com

From zuxoxus at gmail.com  Tue Jul 13 16:43:02 2010
From: zuxoxus at gmail.com (ZUXOXUS)
Date: Tue, 13 Jul 2010 16:43:02 +0200
Subject: [Tutor] I don't understand this code
Message-ID: <AANLkTim2IB_6Xls4QkaUizylUgFM1dcVhaMRgW2qIeSD@mail.gmail.com>

Hi,

I am a true beginner in programming, and im learning with
inventwithpython.com.

There's something I dont understand, and i would really appreciate any help.

In chapter 9, the one about the Hangman game, I don't get the block of code
in line 61

59.  words = 'ant baboon badger bat bear'
60.

   1. def getRandomWord(wordList):
   2.     # This function returns a random string from the passed list of
   strings.
   3.     wordIndex = random.randint(0, len(wordList) - 1)
   4.     return wordList[wordIndex]


The thing is, the "passed list of strings" is called "words", not
"wordList", so I see it shouldn't work.

On the other hand, the variable "wordList" is defined nowhere!

The code is ok, because the program runs ok. So there is somethings that i
dont get.

Thank you very much in advance.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100713/b80e1662/attachment.html>

From stefan_ml at behnel.de  Wed Jul 14 12:40:18 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Wed, 14 Jul 2010 12:40:18 +0200
Subject: [Tutor] I don't understand this code
In-Reply-To: <AANLkTim2IB_6Xls4QkaUizylUgFM1dcVhaMRgW2qIeSD@mail.gmail.com>
References: <AANLkTim2IB_6Xls4QkaUizylUgFM1dcVhaMRgW2qIeSD@mail.gmail.com>
Message-ID: <i1k46i$qf8$1@dough.gmane.org>

ZUXOXUS, 13.07.2010 16:43:
> Hi,
>
> I am a true beginner in programming, and im learning with
> inventwithpython.com.
>
> There's something I dont understand, and i would really appreciate any help.
>
> In chapter 9, the one about the Hangman game, I don't get the block of code
> in line 61
>
> 59.  words = 'ant baboon badger bat bear'
> 60.
>
>     1. def getRandomWord(wordList):
>     2.     # This function returns a random string from the passed list of
>     strings.
>     3.     wordIndex = random.randint(0, len(wordList) - 1)
>     4.     return wordList[wordIndex]
>
>
> The thing is, the "passed list of strings" is called "words", not
> "wordList", so I see it shouldn't work.

I'm pretty sure that's not how it's called. However, you can transform the 
whitespace separated string into a list by calling .split() on it:

     wordList = words.split()

Also, the function above is redundant with the stdlib, use random.choice() 
instead, which does exactly the same thing.

Stefan


From nitinpawar432 at gmail.com  Wed Jul 14 13:01:32 2010
From: nitinpawar432 at gmail.com (Nitin Pawar)
Date: Wed, 14 Jul 2010 16:31:32 +0530
Subject: [Tutor] I don't understand this code
In-Reply-To: <AANLkTim2IB_6Xls4QkaUizylUgFM1dcVhaMRgW2qIeSD@mail.gmail.com>
References: <AANLkTim2IB_6Xls4QkaUizylUgFM1dcVhaMRgW2qIeSD@mail.gmail.com>
Message-ID: <AANLkTilZHEOiad3KAt9DN_T0tjVOcuYBmCmG2qXiMzS_@mail.gmail.com>

I tried replying with inline the questions
read below within your mail

On Tue, Jul 13, 2010 at 8:13 PM, ZUXOXUS <zuxoxus at gmail.com> wrote:

> Hi,
>
> I am a true beginner in programming, and im learning with
> inventwithpython.com.
>
> There's something I dont understand, and i would really appreciate any
> help.
>
> In chapter 9, the one about the Hangman game, I don't get the block of code
> in line 61
>
> 59.  words = 'ant baboon badger bat bear'
> 60.
>
>    1. def getRandomWord(wordList):
>    2.     # This function returns a random string from the passed list of
>    strings.
>    3.     wordIndex = random.randint(0, len(wordList) - 1)
>    4.     return wordList[wordIndex]
>
>
> The thing is, the "passed list of strings" is called "words", not
> "wordList", so I see it shouldn't work.
>

>> wordList is just a parameter defined for the function and the code which
you are showing, it does not call the function anywhere, there should be
another line like

print getRandomWord(words)

>
> On the other hand, the variable "wordList" is defined nowhere!
>

>> You dont have to define the function parameters usually as you can use
them as they are appearing. In this case, wordList is parameter to funtion
which will be replaced with passed value when the function is called


> The code is ok, because the program runs ok. So there is somethings that i
> dont get.
>
> Thank you very much in advance.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Nitin Pawar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/e3e105db/attachment.html>

From __peter__ at web.de  Wed Jul 14 13:08:01 2010
From: __peter__ at web.de (Peter Otten)
Date: Wed, 14 Jul 2010 13:08:01 +0200
Subject: [Tutor] I don't understand this code
References: <AANLkTim2IB_6Xls4QkaUizylUgFM1dcVhaMRgW2qIeSD@mail.gmail.com>
Message-ID: <i1k5q2$1dv$1@dough.gmane.org>

ZUXOXUS wrote:

> Hi,
> 
> I am a true beginner in programming, and im learning with
> inventwithpython.com.
> 
> There's something I dont understand, and i would really appreciate any
> help.
> 
> In chapter 9, the one about the Hangman game, I don't get the block of
> code in line 61
> 
> 59.  words = 'ant baboon badger bat bear'
> 60.
> 
>    1. def getRandomWord(wordList):
>    2.     # This function returns a random string from the passed list of
>    strings.
>    3.     wordIndex = random.randint(0, len(wordList) - 1)
>    4.     return wordList[wordIndex]
> 
> 
> The thing is, the "passed list of strings" is called "words", not
> "wordList", so I see it shouldn't work.
> 
> On the other hand, the variable "wordList" is defined nowhere!
> 
> The code is ok, because the program runs ok. So there is somethings that i
> dont get.
> 
> Thank you very much in advance.

A value can have a different name inside a function when it is passed as a 
parameter. Consider the following session:

>>> def get_first_word(whatever_you_like):
...     return whatever_you_like[0]
...
>>> names = "peter paul mary".split()
>>> words = "nobody expects the spanish inquisition".split()
>>> get_first_word(names)
'peter'
>>> get_first_word(words)
'nobody'

Both the 'names' and the 'words' list of strings are referred to as 
'whatever_you_like' inside the get_first_word() function.

Peter


From michael at shamirlens.co.uk  Wed Jul 14 12:59:44 2010
From: michael at shamirlens.co.uk (Michael M Mason)
Date: Wed, 14 Jul 2010 11:59:44 +0100
Subject: [Tutor] I don't understand this code
In-Reply-To: <AANLkTim2IB_6Xls4QkaUizylUgFM1dcVhaMRgW2qIeSD@mail.gmail.com>
References: <AANLkTim2IB_6Xls4QkaUizylUgFM1dcVhaMRgW2qIeSD@mail.gmail.com>
Message-ID: <2B7AA81C577B0942A14C2B388867E2C71AE9AA@harry.shamirlens.co.uk>

> The thing is, the "passed list of strings" is called "words",
> not "wordList", so I see it shouldn't work.
>
> On the other hand, the variable "wordList" is defined nowhere!

"wordList" is just a name that the function (getRandomWord) uses to
refer to
whatever values get passed to it. Remember that you don't have to put
your
list of words into a variable before you call the function.  You could
just
do this:-

getRandomWord('ant baboon badger bat bear')

...and it will work. Or consider having two or three variables:-

   words     = 'ant baboon badger bat bear'
   mylist    = 'left right backward forward up down'
   morestuff = 'run walk stand sit'

Naturally you can feed any of these into the function:-

   getRandomWord(words)
   getRandomWord(mylist)
   getRandomWord(morestuff)

You can think of "getRandomWord(wordList)" as a convenient
shorthand for:-

   wordList = words     
   getRandomWord(wordList)

Hope this helps

-- 
Michael

From zstumgoren at gmail.com  Wed Jul 14 13:49:46 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Wed, 14 Jul 2010 07:49:46 -0400
Subject: [Tutor] I don't understand this code
In-Reply-To: <2B7AA81C577B0942A14C2B388867E2C71AE9AA@harry.shamirlens.co.uk>
References: <AANLkTim2IB_6Xls4QkaUizylUgFM1dcVhaMRgW2qIeSD@mail.gmail.com>
	<2B7AA81C577B0942A14C2B388867E2C71AE9AA@harry.shamirlens.co.uk>
Message-ID: <AANLkTinh1Bso3jEmoO6MNTVVuSn9c2urOAV3ggYUDB9X@mail.gmail.com>

The rest of the list does a great job explaining the situation, which bears
out in the code itself. If you look farther down in the code sample in
Chapter 9, you'll see the function called twice.

http://inventwithpython.com/chapter9/

<< snipped >>
print('H A N G M A N')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
gameIsDone = False
<< end snippet >>

And then again a bit below:

<< snippet >>

            gameIsDone = False
            secretWord = getRandomWord(words)
        else:
            break

<< end snippet >>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/e1ba3b13/attachment-0001.html>

From alan.gauld at btinternet.com  Wed Jul 14 14:13:42 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Jul 2010 13:13:42 +0100
Subject: [Tutor] Response to responses about list of lists: a
	metaexercise in mailinglist recursion
References: <768895.83808.qm@web44713.mail.sp1.yahoo.com>
	<201007141019.34529.steve@pearwood.info>
Message-ID: <i1k9lj$emo$1@dough.gmane.org>


"Steven D'Aprano" <steve at pearwood.info> wrote

> If you're starting a new discussion, or raising a new question, make 
> a
> fresh, blank email, put a descriptive title in the subject line, and
> put tutor at python.org as the To address.
>
> If you're replying to an existing message, using reply is fine, but 
> just
> trim the quoted text. You have a delete key -- learn how to use it 
> :)

And I'll just add that you should use Reply All not vanilla Reply.
Reply will send your response back to the person who sent the
original message. Reply All sends it, as the name suggests,
to everyone on the list.

HTH,

Alan G. 



From kb1pkl at aim.com  Wed Jul 14 14:18:46 2010
From: kb1pkl at aim.com (Corey Richardson)
Date: Wed, 14 Jul 2010 08:18:46 -0400
Subject: [Tutor] GUI Creation Aide
Message-ID: <4C3DAB26.4070705@aim.com>

Hey tutors! I'm creating a GUI for a program. Really simple. I don't 
mind coding it out, but I was looking into things like Glade and the 
like. Do you recommend those over just coding it out by hand, or should 
I try Glade (or similiar) out? Also, I don't really have a preference 
for which toolkit I use, wx/Tk/GTK, etc.

Thanks,
~Corey Richardson

From alan.gauld at btinternet.com  Wed Jul 14 14:21:39 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Jul 2010 13:21:39 +0100
Subject: [Tutor] I don't understand this code
References: <AANLkTim2IB_6Xls4QkaUizylUgFM1dcVhaMRgW2qIeSD@mail.gmail.com>
Message-ID: <i1ka4g$gbe$1@dough.gmane.org>


"ZUXOXUS" <zuxoxus at gmail.com> wrote

> 59.  words = 'ant baboon badger bat bear'
> 
>   1. def getRandomWord(wordList):
>   3.     wordIndex = random.randint(0, len(wordList) - 1)
>   4.     return wordList[wordIndex]
> 
> 
> The thing is, the "passed list of strings" is called "words", not
> "wordList", so I see it shouldn't work.

Note that wordList appears in the def line.
Have you studied functions yet? (I'm not familiar with your tutorial)
If so you should have read about parammeters or arguments?
parameters are local; variables within the function that take on 
the values passed to the function.

So if we define a function to return the square of a number:

def square(x):
     return x*x

We define the functon to have a parameter x.

When we call the function we must pass in a value for x:

foo = 20
bar = square(foo)

Notice that we pass foo to square() but the value inside 
the function is called x.

Now lets look again at your example:

>   1. def getRandomWord(wordList):
>   3.     wordIndex = random.randint(0, len(wordList) - 1)
>   4.     return wordList[wordIndex]

It has a parameter called wordList. That will take on the 
value passed into it and the reyrn value will be a random 
item from that list.

> On the other hand, the variable "wordList" is defined nowhere!

Yes it is, in the function definition.

So when you call it with

getRandomWord(words)

wordList takes on the value of words.

You can find an alternative explanation of functions, parameters 
and arguments in the "Modules and Functions" topic of my tutorial.

HTH,


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




From alan.gauld at btinternet.com  Wed Jul 14 14:32:24 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Jul 2010 13:32:24 +0100
Subject: [Tutor] Handling 'None' (null) values when processing sqlite
	cursorresults
References: <i1jeji$rho$1@dough.gmane.org>
Message-ID: <i1kaol$ilg$1@dough.gmane.org>


"Monte Milanuk" <memilanuk at gmail.com> wrote

> (104, None, u'Sylvester', None, u'Evans', None, u'527-9210 Proin 
> Av.', u'Liberal', u'VT', u'24742', u'1-135-197-1139', 
> u'vehicula.Pellentesque at idmollis.edu', u'2010-07-13 22:52:50', 
> u'2010-07-13 22:52:50')
>
> At first I was having fits as str.join() was giving me a 'NoneType 
> error'.  I found one way around that, by processing the results so 
> the 'None' values got omitted from the list by the time they got to 
> str.join().

Keep the storage and manipulation of data separate from the
display of that data. That is an important and fundamental principle
of data processing. Store the data with the nulls. Display the data 
without.

> values omitted really messed with the list order which I was 
> depending on i.e. list[5] could be different fields depending on how 
> many 'None'

And that is why.

> values had been omitted.  And if I didn't omit them, when I printed 
> out the user name in the format 'first''middle''last' from the above 
> record,

You need a display function that can strip out the nulls as needed.
A simple list comprehension or generator expression would work
in this case:

print ' '.join(str(field) for field in data if field is not 'None')

If you use a Class to model your data you can write a __str__() method
that does the intellifgent production of a string fit for printing. 
Then you just
print the records as normal. But for this scenario the complexity of 
building
a class may not be worth it.

The key principle is do not try to store your data in a display 
format.


HTH,


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



From mehgcap at gmail.com  Wed Jul 14 14:32:43 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Wed, 14 Jul 2010 08:32:43 -0400
Subject: [Tutor] GUI Creation Aide
In-Reply-To: <4C3DAB26.4070705@aim.com>
References: <4C3DAB26.4070705@aim.com>
Message-ID: <AANLkTilJ37DTV_RGjV4ZwvRarmgnWl8mNpzz01yxGcsI@mail.gmail.com>

On 7/14/10, Corey Richardson <kb1pkl at aim.com> wrote:
> Hey tutors! I'm creating a GUI for a program. Really simple. I don't
> mind coding it out, but I was looking into things like Glade and the
> like. Do you recommend those over just coding it out by hand, or should
> I try Glade (or similiar) out? Also, I don't really have a preference
> for which toolkit I use, wx/Tk/GTK, etc.
I have only ever used wx with the XRCed program, but I really like it.
Learning xrc is pretty straightforward, and there are some good
tutorials for it. It also has the advantage of keeping the code
generating your gui separate from your program, so code management is
easier. I have heard xrc/python compared to css/html regarding code
separation. For a really simple gui it is probably not too important,
but if you do larger projects later on it will probably make life
easier.
>
> Thanks,
> ~Corey Richardson
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From alan.gauld at btinternet.com  Wed Jul 14 14:40:09 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Jul 2010 13:40:09 +0100
Subject: [Tutor] GUI Creation Aide
References: <4C3DAB26.4070705@aim.com>
Message-ID: <i1kb76$k82$1@dough.gmane.org>


"Corey Richardson" <kb1pkl at aim.com> wrote

> Hey tutors! I'm creating a GUI for a program. Really simple. I don't 
> mind coding it out, but I was looking into things like Glade and the 
> like. Do you recommend those over just coding it out by hand, or 
> should I try Glade (or similiar) out? Also, I don't really have a 
> preference for which toolkit I use, wx/Tk/GTK, etc.

I spent some time a couple of years back looking at different GUI
builders for Python. Frankly I didn't like any of them. Nothing comes
close to the tools used in VisualBasic or Delphi etc.

Things may have improved in recent years and there are a few 
commercial
tools that I didn't look at but for my limited GUI programming needs I 
find
I'm just as well hand coding the GUI.

Just a personal view, others may differ. And if you intend to do a lot 
of
GUI work (especially if you get paid for it!)  then it may be worth 
paying for
something that really does a good job.

HTH,

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



From waynejwerner at gmail.com  Wed Jul 14 14:48:04 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Wed, 14 Jul 2010 07:48:04 -0500
Subject: [Tutor] GUI Creation Aide
In-Reply-To: <4C3DAB26.4070705@aim.com>
References: <4C3DAB26.4070705@aim.com>
Message-ID: <AANLkTimFmtMnoocRH-ulj_zmdGkhIricf_5Viuh9z62J@mail.gmail.com>

On Wed, Jul 14, 2010 at 7:18 AM, Corey Richardson <kb1pkl at aim.com> wrote:

> Hey tutors! I'm creating a GUI for a program. Really simple. I don't mind
> coding it out, but I was looking into things like Glade and the like. Do you
> recommend those over just coding it out by hand, or should I try Glade (or
> similiar) out? Also, I don't really have a preference for which toolkit I
> use, wx/Tk/GTK, etc.


Honestly it depends on how "pretty" you want it to look. Tkinter is the
ugliest GUI toolkit, but it's the easiest one to create simple GUIs.  To
create a window with a button with the text "hello world" that quits when
you push the button:

import Tkinter as tk

root = tk.Tk()
btn = tk.Button(root, text="Hello World", command=root.quit)
btn.pack()
root.mainloop()

And it's as simple as that. There are some fairly powerful widgets, but
nothing quite as advanced as you'll find in other frameworks. However, the
other frameworks do a have the benefit of a lot more power, so it really
comes down to what you want and what you need. If you need a simple GUI with
maybe a list or some text entry and some buttons, and maybe a menu, Tk is
the way to go.

If you want an advanced GUI with all sorts of pretty widgets and drawing
capabilities and bells and whistles, wx or GTK (my personal fave) are all
great options.

Of course, it's also my personal opinion that every python programmer should
learn Tkinter - it's a quick and easy way to throw up a GUI - so if you need
to just slap something together, it's right there. Plus it introduces you to
layout managers and callbacks, both of which are super useful programming
GUIs down the road.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/9aaa6863/attachment-0001.html>

From cwitts at compuscan.co.za  Wed Jul 14 14:58:25 2010
From: cwitts at compuscan.co.za (Christian Witts)
Date: Wed, 14 Jul 2010 14:58:25 +0200
Subject: [Tutor] Handling 'None' (null) values when processing sqlite
 cursorresults
In-Reply-To: <i1kaol$ilg$1@dough.gmane.org>
References: <i1jeji$rho$1@dough.gmane.org> <i1kaol$ilg$1@dough.gmane.org>
Message-ID: <4C3DB471.6030203@compuscan.co.za>

On 14/07/2010 14:32, Alan Gauld wrote:
>
> "Monte Milanuk" <memilanuk at gmail.com> wrote
>
>> (104, None, u'Sylvester', None, u'Evans', None, u'527-9210 Proin 
>> Av.', u'Liberal', u'VT', u'24742', u'1-135-197-1139', 
>> u'vehicula.Pellentesque at idmollis.edu', u'2010-07-13 22:52:50', 
>> u'2010-07-13 22:52:50')
>>
>> At first I was having fits as str.join() was giving me a 'NoneType 
>> error'.  I found one way around that, by processing the results so 
>> the 'None' values got omitted from the list by the time they got to 
>> str.join().
>
> Keep the storage and manipulation of data separate from the
> display of that data. That is an important and fundamental principle
> of data processing. Store the data with the nulls. Display the data 
> without.
>
>> values omitted really messed with the list order which I was 
>> depending on i.e. list[5] could be different fields depending on how 
>> many 'None'
>
> And that is why.
>
>> values had been omitted.  And if I didn't omit them, when I printed 
>> out the user name in the format 'first''middle''last' from the above 
>> record,
>
> You need a display function that can strip out the nulls as needed.
> A simple list comprehension or generator expression would work
> in this case:
     print ' '.join(str(field) for field in data if field is not 'None')
>

The problem with that is if you're relying on a set delimiter you are 
removing elements so you would be better served by doing `str(field) if 
field != None else '' for field in record`

-- 
Kind Regards,
Christian Witts



From siren99 at yahoo.com  Wed Jul 14 15:53:38 2010
From: siren99 at yahoo.com (Siren Saren)
Date: Wed, 14 Jul 2010 06:53:38 -0700 (PDT)
Subject: [Tutor] Response to responses about list of lists: a meta
	exercise in mailinglist recursion
In-Reply-To: <mailman.3085.1279072694.1671.tutor@python.org>
Message-ID: <787985.1707.qm@web44714.mail.sp1.yahoo.com>

Steven D'Aprano,

Your response was profoundly helpful to me.? If that sounds grandiose, I mean it nonetheless.? You not only answered all of my specific questions and taught me general methods I will use and reuse, you also gave me some hope.? It's a lonely process teaching myself to program in my mid-thirties. I tend to ask the wrong questions in the wrong way.? Even though I try to read all the FAQs and do 'my homework' before asking something, I still make an unfavorable impression because of errors I didn't even consider, like accidentally attaching all the group's prior messages to my first post here.? 

I thought something in the culture of programming was particularly intolerant of the sort of errors I'd make, perhaps because of the syntactic precision required to program well.? But I realize now, retrospectively, I might have been offending people because I'd often ask questions about how to make something work on windows.? After reading some of the tutor links, I see that there's a cultural anger toward windows, which makes sense.? Anyway between installing ubuntu yesterday and getting your response, I feel more hopeful that I won't need to be quite so isolated in my learning.? Let me buy you a virtual beer.? Thanks again,

Soren ? 


Message: 2
Date: Wed, 14 Jul 2010 10:19:34 +1000
From: Steven D'Aprano <steve at pearwood.info>
To: tutor at python.org
Subject: Re: [Tutor] Response to responses about list of lists: a meta
??? exercise in mailinglist recursion
Message-ID: <201007141019.34529.steve at pearwood.info>
Content-Type: text/plain;? charset="utf-8"

On Tue, 13 Jul 2010 10:40:44 pm Siren Saren wrote:
> I'm not sure if there's a way to submit responses 'live' or
> whether it's better to respond to subthreads at once or together, so
> I'll err on the side of discretion and just send one response.?

Generally it's better, or at least more common, to respond to each 
response individually. But that's generally because people on mailing 
lists receive individual pieces of mail instead of a single giant 
digest containing the entire day's email traffic.


> In response to the first question: the consensus seems to be
> that there is no good way to sort a non-alternating one-to-many list
> like this, so my strategy of deriving the index numbers of every
> item, as awkward as it appears, may actually be the best approach.

No, a better approach is to split the list into separate lists:

mixedlist = [
 'Crime and punishment', 10, 40, 30, 
 "Brother's Karamazov", 22, 55, 9000, 
 "Father's and Sons", 100,
 'Anna Karenina', 1, 2, 4, 7, 9,
]

# untested
current_book = None
current_pages = []
result = []
for item in mixedlist:
? ? # Is it a title, or an integer page?
? ? if isinstance(item, str):
? ? ? ? # It's a title.
? ? ? ? if current_book is not None:
? ? ? ? ? ? result.append( (current_book, current_pages) )
? ? ? ? current_book = item
? ? ? ? current_pages = []
? ? else:
? ? ? ? # It's a page number.
? ? ? ? current_pages.append(item)

This will split the mixed list of titles, page numbers into a 
consolidated list of (title, list-of-page-numbers) like this:

booklist = [
?("Crime and punishment", [10, 40, 30]),
?("Brother's Karamazov", [22, 55, 9000]),
?("Father's and Sons", [100]),
?("Anna Karenina", [1, 2, 4, 7, 9]),
]

It's easy to adapt it to use a dictionary instead of a list. Change 
result to an empty dict {} instead of an empty list [], and change the 
line:

result.append( (current_book, current_pages) )

into:

result[current_book] = current_pages



One other thing... it's possible that your data is provided to you in 
text form, so that you have a single string like:

"Crime and punishment, page 10, page 40, page 30, ..."

instead of the more useful list of titles and integers. Some people have 
suggested using regular expressions to process the page numbers. That's 
fine, but it's rather overkill, like using a bulldozer to move a 
shovelful of dirt. Here's an (untested) filter to convert the one long 
string into a list of titles and integer pages:

result = []
for item in long_string.split(','):
? ? item = item.strip()? # get rid of leading and trailing spaces
? ? if item.startswith('page '):
? ? ? ? item = int(item[5:])
? ? result.append(item)

This assumes the data is well-formed, there are no typos such as "pgae 
15" in the data, and most importantly, no commas in the book titles.

This can be written as a two-liner, at the cost of some readability:

items = [item.strip() for item in long_string.split(',')]
result = [int(s[5:]) if s.startswith('page ') else s for s in items]

Making it into a one-liner is left as an exercise for the masochistic.


This demonstrates the basic principle of data processing of this kind. 
You start with a bunch of data in one form, and you transform it into 
another, slightly different and more useful form, using a series on 
individual filters or transformation functions:

Start with one long string.
Divide it into a list of substrings.
Transform it into a list of strings and integers.
Collate the integers with the string they belong to.
Do something useful with the pairs of (string, list-of-integers)


[...]
> I apologize for using 'reply,' I've never used a mailing
> list before and didn't understand what would happen.

Using rely is fine, but trim your response! Think of it like this. 
Suppose you received dozens of letters each day, from many different 
people, but the post office consolidated it all into a single envelope 
and delivered it once a day (a "digest"). If you wanted to reply to 
something from Fred, you wouldn't photocopy the entire day's collection 
of mail, all two hundred letters, and stick it at the bottom of your 
reply, would you? Well, that's what your mail program does, by default. 
It only takes a second to delete that excess baggage from your reply 
before hitting send.



> Is there some 
> online forum where I could post a message directly rather than
> mailing it in?

I don't think there's an online forum, because this is an email mailing 
list, not a web forum.

If you're starting a new discussion, or raising a new question, make a 
fresh, blank email, put a descriptive title in the subject line, and 
put tutor at python.org as the To address. 

If you're replying to an existing message, using reply is fine, but just 
trim the quoted text. You have a delete key -- learn how to use it :)


> I see that other people are somehow responding to my message from the
> more real-time updates I can get on activestate, but I don't know how
> they are doing it since I haven't received the mailing yet that would
> include my message and its responses.

That's because they'll be subscribed directly to the tutor mailing list, 
and getting individual pieces of mail as they're sent rather than a 
queued up and consolidated digest.


> If my list had a million books in it and 10 million page
> numbers, would the approach I've outlined in my initial post be the
> best for sorting them??

Ten million items isn't much for modern computers with gigabytes of 
memory. It's *approaching* "much", but hasn't quite reached it yet, and 
for most applications, it doesn't matter if it takes 2 seconds to 
pre-process your data instead of 0.5 second, so long as that's a 
one-off cost. If you have to do it again and again, that's another 
thing!





      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/73a5c0f4/attachment.html>

From adam.jtm30 at gmail.com  Wed Jul 14 16:01:30 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Wed, 14 Jul 2010 15:01:30 +0100
Subject: [Tutor] Path?
In-Reply-To: <4C3D1884.8070501@comcast.net>
References: <4C3A0284.6090901@comcast.net>
	<201007120932.06800.steve@pearwood.info> 
	<4C3C6D8C.4090202@comcast.net>
	<AANLkTikF2HzyOLTymwAjcWxr7KPiSNVuQyIhB07DtS_s@mail.gmail.com> 
	<4C3CE854.5060803@comcast.net>
	<AANLkTik6FcbxVzajVr5HDOrG3j5EaJbRk8Uv7SnbQT6k@mail.gmail.com> 
	<4C3D1884.8070501@comcast.net>
Message-ID: <AANLkTikN4PhkIhIYJC3KuPUmteAeGXumnXy7kzcgUkRL@mail.gmail.com>

On 14 July 2010 02:53, Jim Byrnes <jf_byrnes at comcast.net> wrote:

> Adam Bark wrote:
>
> <snipped some old stuff>
>
>
>  If I use the terminal to start the program it has no problem using the
>>>>> file.  There are multiple files in multiple directories so I was
>>>>> looking
>>>>> for
>>>>> a way to just double click them and have them run.  If it turns out
>>>>> that
>>>>> I
>>>>> must make changes to or for each of the files it will be easier to just
>>>>> keep
>>>>> using the terminal.  I've only been using Ubuntu for a few months so I
>>>>> was
>>>>> surprised that the program could not see a file that is in the same
>>>>> directory.
>>>>>
>>>>> Regards,  Jim
>>>>>
>>>>>
>>>>
>>>> The problem is ubuntu doesn't run the script from the directory it's in
>>>> so
>>>> it's looking for wxPython.jpg somewhere else.
>>>>
>>>>
>>>>  OK, I mistakenly thought that double-clicking on file in Nautilus would
>>> take care of the path info.
>>>
>>> In my reply above I also mentioned that I tried by dropping it on a
>>> Launcher on the top panel and that the command the launcher uses is
>>> usr/bin/python2.6.  Is there a way that the command can be changed so
>>> that
>>> it will look in the same directory the python script is in for any file
>>> it
>>> needs?
>>>
>>> Thanks,  Jim
>>>
>>
>>
>> Not sure if you got my previous email but you could try writing the bash
>> script I posted (with the $1 line to get the path) and setting that as
>> your
>> launcher, I think it should work.
>>
>> Let me know if you didn't get it or it doesn't work.
>>
>> HTH,
>> Adam.
>>
>>
> I got it, got sidetracked and then forgot to look at it again.  Thanks for
> reminding me.  Your idea works, but with one little downside.  The
> directories I am working with are chapters in a book.  So as I move from
> chapter to chapter I will need to change the bash script, but this seems to
> be less typing than using the terminal.
>
>
> Thanks,  Jim
>

Ok cool, glad it works. It might be possible to get the path so you don't
have to set it each time, try this:

 #!/bin/bash

IFS="/"
path=($1)
cd $(path[0:#path[*]])
python $1


# Warning, I'm not exactly a competent bash programmer so this may not work
:-p

Let me know if you need a hand to fix it,

HTH,
Adam.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/6be7c7a5/attachment-0001.html>

From steve at pearwood.info  Wed Jul 14 16:21:33 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 15 Jul 2010 00:21:33 +1000
Subject: [Tutor] Response to responses about list of lists: a meta
	exercise in mailinglist recursion
In-Reply-To: <787985.1707.qm@web44714.mail.sp1.yahoo.com>
References: <787985.1707.qm@web44714.mail.sp1.yahoo.com>
Message-ID: <201007150021.34389.steve@pearwood.info>

On Wed, 14 Jul 2010 11:53:38 pm Siren Saren wrote:
> Steven D'Aprano,
>
> Your response was profoundly helpful to me.
[...]

Thank you for the kind words, and cheers! I wish you good fortunate and 
a lot of fun in your endeavour.

> I thought something in the culture of programming was particularly
> intolerant of the sort of errors I'd make, perhaps because of the
> syntactic precision required to program well.

Programmers, especially *mediocre* programmers, are often well known for 
their arrogance and rudeness. Sometimes this arrogance is justified; 
often it is not.

Remember also that, sadly, the Internet encourages rudeness. You can 
easily fire off an instant response without thinking about the 
consequences; there is anonymity and the urge to show off; there is the 
urge to win the argument no matter what. I admit that sometimes I fall 
into this trap myself. If I've had a bad day at work, or have had to 
put up with one too many annoyance, sometimes I might be a bit 
short-tempered. I would like to hope only at those who deserve it, but 
I'm only human.

But fortunately, the Python community is usually much, much friendlier 
than some other places. Perhaps that's because Python is a programming 
language designed to be usable by people of all levels, from beginners 
and children to programming geniuses. With a willingness to learn and a 
little bit of care, I am sure you will be fine.

You might like to read this:

http://catb.org/esr/faqs/smart-questions.html

Take it with a grain of salt -- not every smart programmer or hacker is 
as anti-social as described, but nevertheless, the basic principles are 
sound.



-- 
Steven D'Aprano

From kb1pkl at aim.com  Wed Jul 14 16:18:58 2010
From: kb1pkl at aim.com (Corey Richardson)
Date: Wed, 14 Jul 2010 10:18:58 -0400
Subject: [Tutor] Global name not found, though clearly in use
Message-ID: <4C3DC752.1090405@aim.com>

Hey tutors. Two separate submissions one day, guess I'm getting busy ;)

Anyway, I'm re-writing my hangman program to make use of my new-found 
understanding of OOP, and using a GUI this time around. I decided on 
coding with Tkinter, to get my feet wet with GUI stuff.
Here is the traceback:

Traceback (most recent call last):
  File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__
    return self.func(*args)
  File "C:/Users/Corey/Desktop/HangmanApp.py", line 45, in getLetter
    self.guess = eWordEntryBox.get()
NameError: global name 'eWordEntryBox' is not defined

However, not even 30 lines down, (29, to be exact) there is this line:
    eWordEntryBox = tk.Entry(fWordEntry)

Not understanding what is happening here. Same happens when I tack self 
at the beginning of it, except it says global name self is not defined.

Thanks!
~Corey Richardson

From nitinpawar432 at gmail.com  Wed Jul 14 16:31:47 2010
From: nitinpawar432 at gmail.com (Nitin Pawar)
Date: Wed, 14 Jul 2010 20:01:47 +0530
Subject: [Tutor] Global name not found, though clearly in use
In-Reply-To: <4C3DC752.1090405@aim.com>
References: <4C3DC752.1090405@aim.com>
Message-ID: <AANLkTimtppor6--H0_Bx1mitJsr7o_CLn1Jajju6PCx5@mail.gmail.com>

>From the logs looks like the variable is not initiated when it was used.

If I read it correct, you said it down ... that means below the line where
the error came? and if they belong to same function then this error is valid

Thanks,
Nitin

On Wed, Jul 14, 2010 at 7:48 PM, Corey Richardson <kb1pkl at aim.com> wrote:

> Hey tutors. Two separate submissions one day, guess I'm getting busy ;)
>
> Anyway, I'm re-writing my hangman program to make use of my new-found
> understanding of OOP, and using a GUI this time around. I decided on coding
> with Tkinter, to get my feet wet with GUI stuff.
> Here is the traceback:
>
> Traceback (most recent call last):
>  File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__
>   return self.func(*args)
>  File "C:/Users/Corey/Desktop/HangmanApp.py", line 45, in getLetter
>   self.guess = eWordEntryBox.get()
> NameError: global name 'eWordEntryBox' is not defined
>
> However, not even 30 lines down, (29, to be exact) there is this line:
>   eWordEntryBox = tk.Entry(fWordEntry)
>
> Not understanding what is happening here. Same happens when I tack self at
> the beginning of it, except it says global name self is not defined.
>
> Thanks!
> ~Corey Richardson
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Nitin Pawar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/96df4e98/attachment.html>

From vineethrakesh at gmail.com  Wed Jul 14 17:11:58 2010
From: vineethrakesh at gmail.com (Vineeth Rakesh)
Date: Wed, 14 Jul 2010 11:11:58 -0400
Subject: [Tutor] Help execution time calculation:
Message-ID: <AANLkTinNR34WgzVo0p2mGLkWUXfNHkI33mFxisG88xcF@mail.gmail.com>

Hello all,

I want to calculate the execution time of a program. Say I have a function
like below:

def RepAdd(i):
  j = 0
  while(j<i):
     j += 1
  return j

now I want to calculate the execution time of the function RepAdd when say
10 is passed as an argument. I did come across the module timeit, if that is
the module to be used can any one illustrate it using the above program as
input.

Thanks
Vin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/7d28a711/attachment.html>

From steve at pearwood.info  Wed Jul 14 17:17:53 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 15 Jul 2010 01:17:53 +1000
Subject: [Tutor] Global name not found, though clearly in use
In-Reply-To: <4C3DC752.1090405@aim.com>
References: <4C3DC752.1090405@aim.com>
Message-ID: <201007150117.54247.steve@pearwood.info>

On Thu, 15 Jul 2010 12:18:58 am Corey Richardson wrote:
> Hey tutors. Two separate submissions one day, guess I'm getting busy
> ;)
>
> Anyway, I'm re-writing my hangman program to make use of my new-found
> understanding of OOP, and using a GUI this time around. I decided on
> coding with Tkinter, to get my feet wet with GUI stuff.

With respect, I'm not sure your new-found understanding is that 
complete, if you're having problems with simple variables. Have you 
considered doing some basic tutorials to ensure your understanding of 
Python has a solid foundation?

> Here is the traceback:
>
> Traceback (most recent call last):
>   File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__
>     return self.func(*args)
>   File "C:/Users/Corey/Desktop/HangmanApp.py", line 45, in getLetter
>     self.guess = eWordEntryBox.get()
> NameError: global name 'eWordEntryBox' is not defined
>
> However, not even 30 lines down, (29, to be exact) there is this
> line: eWordEntryBox = tk.Entry(fWordEntry)

Without seeing your actual code, it's impossible to say what's going on 
except in vague generalities. But consider a program made of just TWO 
lines:

print(x)
x = 1

What do you expect will happen? If you are surprised that Python will 
raise NameError when it tries to print the value of x, then you really 
should do some basic tutorials.

At the point that the line "print x" is called, x hasn't been defined 
*yet*, and so it doesn't exist. My guess is that your error is exactly 
the same -- you might have a line that defines eWordEntryBox 29 lines 
further down, but at the point that the error occurs, that line hasn't 
been reached yet, and so eWordEntryBox doesn't exist:

self.guess = eWordEntryBox.get()  # Error occurs here
...
...
29 lines of code
...
...
eWordEntryBox = tk.Entry(fWordEntry)  # Defined for the first time!


> Not understanding what is happening here. Same happens when I tack
> self at the beginning of it, except it says global name self is not
> defined.

You can't just "tack" self at the beginning of variables and expect it 
to work, any more than you could tack on "akjfhbcvgsaj" and hope for 
the best! You need to understand *where* the variable self exists, and 
*what* value it has.




-- 
Steven D'Aprano

From steve at pearwood.info  Wed Jul 14 17:23:26 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 15 Jul 2010 01:23:26 +1000
Subject: [Tutor] Help execution time calculation:
In-Reply-To: <AANLkTinNR34WgzVo0p2mGLkWUXfNHkI33mFxisG88xcF@mail.gmail.com>
References: <AANLkTinNR34WgzVo0p2mGLkWUXfNHkI33mFxisG88xcF@mail.gmail.com>
Message-ID: <201007150123.27182.steve@pearwood.info>

On Thu, 15 Jul 2010 01:11:58 am Vineeth Rakesh wrote:
> Hello all,
>
> I want to calculate the execution time of a program. Say I have a
> function like below:
>
> def RepAdd(i):
>   j = 0
>   while(j<i):
>      j += 1
>   return j
>
> now I want to calculate the execution time of the function RepAdd
> when say 10 is passed as an argument. I did come across the module
> timeit, if that is the module to be used can any one illustrate it
> using the above program as input.

timeit is the *right* solution for timing small code snippets like 
RepAdd above, but the recipe for using it can appear a little 
mysterious.

If you have RepAdd in a file "test.py", then from the command line:

python -m timeit -s "from test import RepAdd" "RepAdd(10)"

should work.

Otherwise, type RepAdd into the Python interactive interpreter, or into 
IDLE, and then do this:

from timeit import Timer
t = Timer('RepAdd(10)', 'from __main__ import RepAdd')
print(min(t.repeat()))



-- 
Steven D'Aprano

From kb1pkl at aim.com  Wed Jul 14 17:31:48 2010
From: kb1pkl at aim.com (Corey Richardson)
Date: Wed, 14 Jul 2010 11:31:48 -0400
Subject: [Tutor] Global name not found, though clearly in use
Message-ID: <4C3DD864.1010505@aim.com>

  I was under the impression that when you define a function, it doesn't 
try to evaluate anything yet. If I had called the function before I 
defined the variable, I would understand, but I haven't. The entirety of 
my (incomplete and buggy) code is now available here: 
http://pastebin.com/QTNmKYC6

Steven D'Aprano wrote:
> On Thu, 15 Jul 2010 12:18:58 am Corey Richardson wrote:
>   
>> Hey tutors. Two separate submissions one day, guess I'm getting busy
>> ;)
>>
>> Anyway, I'm re-writing my hangman program to make use of my new-found
>> understanding of OOP, and using a GUI this time around. I decided on
>> coding with Tkinter, to get my feet wet with GUI stuff.
>>     
>
> With respect, I'm not sure your new-found understanding is that 
> complete, if you're having problems with simple variables. Have you 
> considered doing some basic tutorials to ensure your understanding of 
> Python has a solid foundation?
>
>   
>> Here is the traceback:
>>
>> Traceback (most recent call last):
>>   File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__
>>     return self.func(*args)
>>   File "C:/Users/Corey/Desktop/HangmanApp.py", line 45, in getLetter
>>     self.guess = eWordEntryBox.get()
>> NameError: global name 'eWordEntryBox' is not defined
>>
>> However, not even 30 lines down, (29, to be exact) there is this
>> line: eWordEntryBox = tk.Entry(fWordEntry)
>>     
>
> Without seeing your actual code, it's impossible to say what's going on 
> except in vague generalities. But consider a program made of just TWO 
> lines:
>
> print(x)
> x = 1
>
> What do you expect will happen? If you are surprised that Python will 
> raise NameError when it tries to print the value of x, then you really 
> should do some basic tutorials.
>
> At the point that the line "print x" is called, x hasn't been defined 
> *yet*, and so it doesn't exist. My guess is that your error is exactly 
> the same -- you might have a line that defines eWordEntryBox 29 lines 
> further down, but at the point that the error occurs, that line hasn't 
> been reached yet, and so eWordEntryBox doesn't exist:
>
> self.guess = eWordEntryBox.get()  # Error occurs here
> ...
> ...
> 29 lines of code
> ...
> ...
> eWordEntryBox = tk.Entry(fWordEntry)  # Defined for the first time!
>
>
>   
>> Not understanding what is happening here. Same happens when I tack
>> self at the beginning of it, except it says global name self is not
>> defined.
>>     
>
> You can't just "tack" self at the beginning of variables and expect it 
> to work, any more than you could tack on "akjfhbcvgsaj" and hope for 
> the best! You need to understand *where* the variable self exists, and 
> *what* value it has.
>
>
>
>
>   
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/9b3ca410/attachment.html>

From ehamiter at gmail.com  Wed Jul 14 17:46:20 2010
From: ehamiter at gmail.com (Eric Hamiter)
Date: Wed, 14 Jul 2010 10:46:20 -0500
Subject: [Tutor] Searching a text file's contents and comparing them to a
	list
Message-ID: <AANLkTilsE1A5hTbLHDgCK1c91DS43WhOGVp1DcKUmDPx@mail.gmail.com>

Hi all,

New programmer here. This is what I want to do:

1. Open an existing text file named "grocery_list.txt", which has one
item per line, like so:

butter
juice
bread
asparagus
magazines
ice cream

2. ...and search for these items in a pre-defined list.

But I can't seem to get this working. Right now after trying the following:


aisle_one = ["chips", "bread", "pretzels", "magazines"]

grocery_list = open("grocery_list.txt", "r")
for line in grocery_list.readlines():
    if line in aisle_one:
       print "success"
    else:
       print "no joy"
grocery_list.close()


I get this:

no joy
no joy
no joy
no joy
no joy
no joy

when I'm expecting this:

no joy
no joy
success
no joy
success
no joy


Am I close? This seems like it should work but I'm obviously missing something.

Thanks,

Eric

From emile at fenx.com  Wed Jul 14 17:54:47 2010
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 14 Jul 2010 08:54:47 -0700
Subject: [Tutor] Global name not found, though clearly in use
In-Reply-To: <4C3DD864.1010505@aim.com>
References: <4C3DD864.1010505@aim.com>
Message-ID: <i1kmmv$78s$1@dough.gmane.org>

On 7/14/2010 8:31 AM Corey Richardson said...
> I was under the impression that when you define a function, it doesn't
> try to evaluate anything yet. If I had called the function before I
> defined the variable, I would understand, but I haven't.


The difference is in understanding what's executed and what's deferred.

Consider the following:

#-----Start File test.py-----
def test():
   print "in def test"

class Test:
   print "in class Test"
   def __init__(self):
     print "in class Test.__init__"

print "in __main__"

test()
t = Test()

#-----End File test.py-----

Output:

in class Test
in __main__
in def test
in class Test.__init__

-----------------

As you can see, the print statements at the class level are executing 
when encountered, but the prints in defs only when executed.

HTH,

Emile



From emile at fenx.com  Wed Jul 14 18:02:53 2010
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 14 Jul 2010 09:02:53 -0700
Subject: [Tutor] Searching a text file's contents and comparing them to
	a list
In-Reply-To: <AANLkTilsE1A5hTbLHDgCK1c91DS43WhOGVp1DcKUmDPx@mail.gmail.com>
References: <AANLkTilsE1A5hTbLHDgCK1c91DS43WhOGVp1DcKUmDPx@mail.gmail.com>
Message-ID: <i1kn65$90i$1@dough.gmane.org>

On 7/14/2010 8:46 AM Eric Hamiter said...
> Hi all,
>
> New programmer here. This is what I want to do:
>
> 1. Open an existing text file named "grocery_list.txt", which has one
> item per line, like so:
>
> butter
> juice
> bread
> asparagus
> magazines
> ice cream
>
> 2. ...and search for these items in a pre-defined list.
>
> But I can't seem to get this working. Right now after trying the following:
>
>
> aisle_one = ["chips", "bread", "pretzels", "magazines"]
>
> grocery_list = open("grocery_list.txt", "r")
> for line in grocery_list.readlines():
>      if line in aisle_one:

So it's failing this test.

>         print "success"
>      else:
>         print "no joy"

Try adding some debugging code here, maybe changing the print to:
           print "no joy matching %s" % line

Then read up on readlines and string.strip.

HTH,

Emile



From ehamiter at gmail.com  Wed Jul 14 18:22:33 2010
From: ehamiter at gmail.com (Eric Hamiter)
Date: Wed, 14 Jul 2010 11:22:33 -0500
Subject: [Tutor] Searching a text file's contents and comparing them to
	a list
In-Reply-To: <i1kn65$90i$1@dough.gmane.org>
References: <AANLkTilsE1A5hTbLHDgCK1c91DS43WhOGVp1DcKUmDPx@mail.gmail.com> 
	<i1kn65$90i$1@dough.gmane.org>
Message-ID: <AANLkTinlo6pCcoELrtWx7zthacfxSZHELZRVPcEX9eI-@mail.gmail.com>

Fantastic! I have this, which now works. Is there a better place to put
string.strip?

aisle_one = ["chips", "bread", "pretzels", "magazines"]

grocery_list = open("grocery_list.txt", "r")
for line in grocery_list.readlines():
    if line.strip() in aisle_one:
       print "success! i found %s" % line
    else:
       print "no joy matching %s" % line
grocery_list.close()


Thanks Emile.


On Wed, Jul 14, 2010 at 11:02 AM, Emile van Sebille <emile at fenx.com> wrote:


> Try adding some debugging code here, maybe changing the print to:
>          print "no joy matching %s" % line
>
> Then read up on readlines and string.strip.
>
> HTH,
>
> Emile
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/ab85039c/attachment.html>

From kb1pkl at aim.com  Wed Jul 14 18:33:01 2010
From: kb1pkl at aim.com (Corey Richardson)
Date: Wed, 14 Jul 2010 12:33:01 -0400
Subject: [Tutor] Global name not found, though clearly in use
Message-ID: <4C3DE6BD.3000703@aim.com>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/5819a3e5/attachment-0001.html>

From jf_byrnes at comcast.net  Wed Jul 14 18:41:22 2010
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Wed, 14 Jul 2010 11:41:22 -0500
Subject: [Tutor] Path?
In-Reply-To: <AANLkTikN4PhkIhIYJC3KuPUmteAeGXumnXy7kzcgUkRL@mail.gmail.com>
References: <4C3A0284.6090901@comcast.net>
	<201007120932.06800.steve@pearwood.info>
	<4C3C6D8C.4090202@comcast.net>
	<AANLkTikF2HzyOLTymwAjcWxr7KPiSNVuQyIhB07DtS_s@mail.gmail.com>
	<4C3CE854.5060803@comcast.net>
	<AANLkTik6FcbxVzajVr5HDOrG3j5EaJbRk8Uv7SnbQT6k@mail.gmail.com>
	<4C3D1884.8070501@comcast.net>
	<AANLkTikN4PhkIhIYJC3KuPUmteAeGXumnXy7kzcgUkRL@mail.gmail.com>
Message-ID: <4C3DE8B2.7000206@comcast.net>

Adam Bark wrote:
> On 14 July 2010 02:53, Jim Byrnes<jf_byrnes at comcast.net>  wrote:
>
>> Adam Bark wrote:
>>
>> <snipped some old stuff>
>>
>>
>>   If I use the terminal to start the program it has no problem using the
>>>>>> file.  There are multiple files in multiple directories so I was
>>>>>> looking
>>>>>> for
>>>>>> a way to just double click them and have them run.  If it turns out
>>>>>> that
>>>>>> I
>>>>>> must make changes to or for each of the files it will be easier to just
>>>>>> keep
>>>>>> using the terminal.  I've only been using Ubuntu for a few months so I
>>>>>> was
>>>>>> surprised that the program could not see a file that is in the same
>>>>>> directory.
>>>>>>
>>>>>> Regards,  Jim
>>>>>>
>>>>>>
>>>>>
>>>>> The problem is ubuntu doesn't run the script from the directory it's in
>>>>> so
>>>>> it's looking for wxPython.jpg somewhere else.
>>>>>
>>>>>
>>>>>   OK, I mistakenly thought that double-clicking on file in Nautilus would
>>>> take care of the path info.
>>>>
>>>> In my reply above I also mentioned that I tried by dropping it on a
>>>> Launcher on the top panel and that the command the launcher uses is
>>>> usr/bin/python2.6.  Is there a way that the command can be changed so
>>>> that
>>>> it will look in the same directory the python script is in for any file
>>>> it
>>>> needs?
>>>>
>>>> Thanks,  Jim
>>>>
>>>
>>>
>>> Not sure if you got my previous email but you could try writing the bash
>>> script I posted (with the $1 line to get the path) and setting that as
>>> your
>>> launcher, I think it should work.
>>>
>>> Let me know if you didn't get it or it doesn't work.
>>>
>>> HTH,
>>> Adam.
>>>
>>>
>> I got it, got sidetracked and then forgot to look at it again.  Thanks for
>> reminding me.  Your idea works, but with one little downside.  The
>> directories I am working with are chapters in a book.  So as I move from
>> chapter to chapter I will need to change the bash script, but this seems to
>> be less typing than using the terminal.
>>
>>
>> Thanks,  Jim
>>
>
> Ok cool, glad it works. It might be possible to get the path so you don't
> have to set it each time, try this:
>
> #!/bin/bash
> IFS="/"
> path=($1)
> cd $(path[0:#path[*]])
> python $1
>
>
> # Warning, I'm not exactly a competent bash programmer so this may not work
> :-p
>
> Let me know if you need a hand to fix it,
>
> HTH,
> Adam.
>

I tried the new bash code but when I dropped a file on the launcher it 
just flashed an gave no output.  So I tried running the bash script 
(name=runpython) in a terminal and got this error:

/home/jfb/runpython: line 4: path[0:#path[*]]: command not found
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>>

I know even less about bash than you do, so I don't where to start to 
debug this.

Thanks,  Jim


From emile at fenx.com  Wed Jul 14 18:55:29 2010
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 14 Jul 2010 09:55:29 -0700
Subject: [Tutor] Searching a text file's contents and comparing them to
	a list
In-Reply-To: <AANLkTinlo6pCcoELrtWx7zthacfxSZHELZRVPcEX9eI-@mail.gmail.com>
References: <AANLkTilsE1A5hTbLHDgCK1c91DS43WhOGVp1DcKUmDPx@mail.gmail.com>
	<i1kn65$90i$1@dough.gmane.org>
	<AANLkTinlo6pCcoELrtWx7zthacfxSZHELZRVPcEX9eI-@mail.gmail.com>
Message-ID: <i1kq8p$ke0$1@dough.gmane.org>

On 7/14/2010 9:22 AM Eric Hamiter said...
> Fantastic! I have this, which now works. Is there a better place to put
> string.strip?

I might make the changes below, but there's nothing wrong with the way 
you've got it.

>
> aisle_one = ["chips", "bread", "pretzels", "magazines"]
>
> grocery_list = open("grocery_list.txt", "r")

grocery_list= [ item.strip()
    for item in open("grocery_list.txt", "r").readlines() ]

> for line in grocery_list.readlines():

for item in grocery_list:

>      if line.strip() in aisle_one:

     if item in aisle_one:

>         print "success! i found %s" % line
>      else:
>         print "no joy matching %s" % line
> grocery_list.close()
>
>


From davea at ieee.org  Wed Jul 14 19:06:34 2010
From: davea at ieee.org (Dave Angel)
Date: Wed, 14 Jul 2010 13:06:34 -0400
Subject: [Tutor] Global name not found, though clearly in use
In-Reply-To: <4C3DE6BD.3000703@aim.com>
References: <4C3DE6BD.3000703@aim.com>
Message-ID: <4C3DEE9A.8040506@ieee.org>

Corey Richardson wrote:
> The entirety of 
> my (incomplete and buggy) code is now available here: 
> http://pastebin.com/QTNmKYC6  ......
> Hmm..If I add a few debugging lines like that into my code, I get this:
>
> Starting program
> In class Hangman
> done defs in class
> eWordEntryBox defined
> Exception in Tkinter callback
> Traceback (most recent call last):
>  File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__
>    return self.func(*args)
>  File "C:/Users/Corey/Desktop/HangmanApp.py", line 48, in getLetter
>    self.guess = eWordEntryBox.get()
> NameError: global name 'eWordEntryBox' is not defined
>
> <snip>
>   
Why do you indent the main code in this file?  In particular, you've 
defined the lines starting at

   1.
      top = tk.Tk()
   2.
      F = tk.Frame(top)
   3.
      F.pack()

as part of the class, rather than at top-level.  Therefore the 
eWordEntryBox is a class attribute, rather than a global symbol.

I think you need to unindent those lines, so they'll be module-level code.

There are a bunch more problems with the code, starting with the fact 
that you never instantiate a Hangman instance, and continuing to missing 
self parameters on some of the methods.

DaveA




From alan.gauld at btinternet.com  Wed Jul 14 19:13:21 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Jul 2010 18:13:21 +0100
Subject: [Tutor] Global name not found, though clearly in use
References: <4C3DD864.1010505@aim.com>
Message-ID: <i1kr7f$o83$1@dough.gmane.org>


"Corey Richardson" <kb1pkl at aim.com> wrote

> defined the variable, I would understand, but I haven't. The 
> entirety of
> my (incomplete and buggy) code is now available here:
> http://pastebin.com/QTNmKYC6

There are quite a few errors here, one is that many of your class's 
methods
don't have self as their first parameter, rendering them pretty 
useless.
Also you do not create an instance of the class Hangman anywhere.

The only access of eWordEntryBox seems to be in the getletter()
function (one of those weith no self). But that should only cause
an error when called...which it never is.

Are you sure thats the code that is creating the error message?

Alan G. 



From emile at fenx.com  Wed Jul 14 19:19:43 2010
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 14 Jul 2010 10:19:43 -0700
Subject: [Tutor] Global name not found, though clearly in use
In-Reply-To: <4C3DE6BD.3000703@aim.com>
References: <4C3DE6BD.3000703@aim.com>
Message-ID: <i1krma$pv2$1@dough.gmane.org>

On 7/14/2010 9:33 AM Corey Richardson said...
> Hmm..If I add a few debugging lines like that into my code, I get this:

The point was that statements in a class at class level (ie, not in 
defs) are executed sequentially and expect referenced variables to exist 
(ie, defined somewhere 'above' the current statement) -- there is no 
forward peeking going on.  Statements within def's (think 'deferred 
execution' if it helps) expect that the variables referred to will exist 
by the time the def is invoked.

Python executes code top to bottom.  def's create an executable object 
and defers execution until invoked.  Other statements execute when 
encountered.  The statements in your class that start

     top = tk.Tk()
thru...
     F.mainloop()

execute in top-down sequence as they are outside of def's.  That's your 
problem.  It's unusual to have that done within a class definition and I 
expect it shouldn't be there.

HTH,

Emile


From alan.gauld at btinternet.com  Wed Jul 14 19:26:56 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Jul 2010 18:26:56 +0100
Subject: [Tutor] Searching a text file's contents and comparing them toa
	list
References: <AANLkTilsE1A5hTbLHDgCK1c91DS43WhOGVp1DcKUmDPx@mail.gmail.com>
	<i1kn65$90i$1@dough.gmane.org>
	<AANLkTinlo6pCcoELrtWx7zthacfxSZHELZRVPcEX9eI-@mail.gmail.com>
Message-ID: <i1ks0u$r5j$1@dough.gmane.org>


"Eric Hamiter" <ehamiter at gmail.com> wrote

> Fantastic! I have this, which now works. Is there a better place to 
> put
> string.strip?

Its largely a matter of taste and how you intend using the value.

> aisle_one = ["chips", "bread", "pretzels", "magazines"]
>
> grocery_list = open("grocery_list.txt", "r")
> for line in grocery_list.readlines():

You could improve that with

for line in open('grocery_list.txt'):

ie no need for readlines()

Or if using recent(post 2.5) versions of Python you could use with:

with open('grocery_list.txt') as grocery_list:
      for line in grocery_list:

which will ensure the file is closed correctly without you
having to do it yourself. This is probably the best option.

>    if line.strip() in aisle_one:
>       print "success! i found %s" % line

If you never need a stripped version of line again, or if you
are planning on writing it out to another file then this is fine.
If you are going to use it again its probably better to strip()
and asign to itelf:

line = line.strip()

Also you might find rstrip() slightly safer if you have any
unusual characters at the start of line...

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



From alan.gauld at btinternet.com  Wed Jul 14 19:34:59 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Jul 2010 18:34:59 +0100
Subject: [Tutor] Handling 'None' (null) values when processing sqlite
	cursorresults
References: <i1jeji$rho$1@dough.gmane.org> <i1kaol$ilg$1@dough.gmane.org>
	<4C3DB471.6030203@compuscan.co.za>
Message-ID: <i1ksg0$sv0$1@dough.gmane.org>


"Christian Witts" <cwitts at compuscan.co.za> wrote

>> You need a display function that can strip out the nulls as needed.
>> A simple list comprehension or generator expression would work
>> in this case:
>     print ' '.join(str(field) for field in data if field is not 
> 'None')
>
> The problem with that is if you're relying on a set delimiter you 
> are removing elements so you would be better served by doing 
> `str(field) if field != None else '' for field in record`

True, although in this case we do seem to have a fixed condition
since it's the database's representation of null but I originally 
didn't
notice the quotes around None. When I fixed that I should have
changed is to equals..

>     print ' '.join(str(field) for field in data if field != 'None')

But your modification confuses me. can you explain?
What would the print line look like?

Alan G. 



From ehamiter at gmail.com  Wed Jul 14 19:39:29 2010
From: ehamiter at gmail.com (Eric Hamiter)
Date: Wed, 14 Jul 2010 12:39:29 -0500
Subject: [Tutor] Searching a text file's contents and comparing them toa
	list
In-Reply-To: <i1ks0u$r5j$1@dough.gmane.org>
References: <AANLkTilsE1A5hTbLHDgCK1c91DS43WhOGVp1DcKUmDPx@mail.gmail.com> 
	<i1kn65$90i$1@dough.gmane.org>
	<AANLkTinlo6pCcoELrtWx7zthacfxSZHELZRVPcEX9eI-@mail.gmail.com> 
	<i1ks0u$r5j$1@dough.gmane.org>
Message-ID: <AANLkTinQlMRNaLoVxCsXEBl6Lw0zALJzH3sFoF4TNc0Q@mail.gmail.com>

On Wed, Jul 14, 2010 at 12:26 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

>
> If you never need a stripped version of line again, or if you
> are planning on writing it out to another file then this is fine.
> If you are going to use it again its probably better to strip()
> and asign to itelf:
>
> line = line.strip()
>
> Also you might find rstrip() slightly safer if you have any
> unusual characters at the start of line...
>

Thanks for the tip Alan, I think I'll assign it to itself.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/25812655/attachment.html>

From adam.jtm30 at gmail.com  Wed Jul 14 19:56:57 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Wed, 14 Jul 2010 18:56:57 +0100
Subject: [Tutor] Path?
In-Reply-To: <4C3DE8B2.7000206@comcast.net>
References: <4C3A0284.6090901@comcast.net>
	<201007120932.06800.steve@pearwood.info> 
	<4C3C6D8C.4090202@comcast.net>
	<AANLkTikF2HzyOLTymwAjcWxr7KPiSNVuQyIhB07DtS_s@mail.gmail.com> 
	<4C3CE854.5060803@comcast.net>
	<AANLkTik6FcbxVzajVr5HDOrG3j5EaJbRk8Uv7SnbQT6k@mail.gmail.com> 
	<4C3D1884.8070501@comcast.net>
	<AANLkTikN4PhkIhIYJC3KuPUmteAeGXumnXy7kzcgUkRL@mail.gmail.com> 
	<4C3DE8B2.7000206@comcast.net>
Message-ID: <AANLkTimNfk56PblsqqfM_RxlRViWGQd7RX2WGMxxxmHT@mail.gmail.com>

On 14 July 2010 17:41, Jim Byrnes <jf_byrnes at comcast.net> wrote:

> Adam Bark wrote:
>
>> On 14 July 2010 02:53, Jim Byrnes<jf_byrnes at comcast.net>  wrote:
>>
>>  Adam Bark wrote:
>>>
>>> <snipped some old stuff>
>>>
>>>
>>>  If I use the terminal to start the program it has no problem using the
>>>
>>>>  file.  There are multiple files in multiple directories so I was
>>>>>>> looking
>>>>>>> for
>>>>>>> a way to just double click them and have them run.  If it turns out
>>>>>>> that
>>>>>>> I
>>>>>>> must make changes to or for each of the files it will be easier to
>>>>>>> just
>>>>>>> keep
>>>>>>> using the terminal.  I've only been using Ubuntu for a few months so
>>>>>>> I
>>>>>>> was
>>>>>>> surprised that the program could not see a file that is in the same
>>>>>>> directory.
>>>>>>>
>>>>>>> Regards,  Jim
>>>>>>>
>>>>>>>
>>>>>>>
>>>>>> The problem is ubuntu doesn't run the script from the directory it's
>>>>>> in
>>>>>> so
>>>>>> it's looking for wxPython.jpg somewhere else.
>>>>>>
>>>>>>
>>>>>>  OK, I mistakenly thought that double-clicking on file in Nautilus
>>>>>> would
>>>>>>
>>>>> take care of the path info.
>>>>>
>>>>> In my reply above I also mentioned that I tried by dropping it on a
>>>>> Launcher on the top panel and that the command the launcher uses is
>>>>> usr/bin/python2.6.  Is there a way that the command can be changed so
>>>>> that
>>>>> it will look in the same directory the python script is in for any file
>>>>> it
>>>>> needs?
>>>>>
>>>>> Thanks,  Jim
>>>>>
>>>>>
>>>>
>>>> Not sure if you got my previous email but you could try writing the bash
>>>> script I posted (with the $1 line to get the path) and setting that as
>>>> your
>>>> launcher, I think it should work.
>>>>
>>>> Let me know if you didn't get it or it doesn't work.
>>>>
>>>> HTH,
>>>> Adam.
>>>>
>>>>
>>>>  I got it, got sidetracked and then forgot to look at it again.  Thanks
>>> for
>>> reminding me.  Your idea works, but with one little downside.  The
>>> directories I am working with are chapters in a book.  So as I move from
>>> chapter to chapter I will need to change the bash script, but this seems
>>> to
>>> be less typing than using the terminal.
>>>
>>>
>>> Thanks,  Jim
>>>
>>>
>> Ok cool, glad it works. It might be possible to get the path so you don't
>> have to set it each time, try this:
>>
>> #!/bin/bash
>> IFS="/"
>> path=($1)
>> cd $(path[0:#path[*]])
>> python $1
>>
>>
>> # Warning, I'm not exactly a competent bash programmer so this may not
>> work
>> :-p
>>
>> Let me know if you need a hand to fix it,
>>
>> HTH,
>> Adam.
>>
>>
> I tried the new bash code but when I dropped a file on the launcher it just
> flashed an gave no output.  So I tried running the bash script
> (name=runpython) in a terminal and got this error:
>
> /home/jfb/runpython: line 4: path[0:#path[*]]: command not found
> Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
> [GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>>
>
> I know even less about bash than you do, so I don't where to start to debug
> this.
>
>
> Thanks,  Jim
>
> Ok then, this time it's tested and not just improvised, here we go:

#!/bin/bash

script=$1 # Full path for calling the script later
orig_IFS=$IFS # This is to reset IFS so that "script" is correct (otherwise
has spaces instead of /)
IFS="/"
path=( $1 )
IFS=$orig_IFS
last_ind=${#path[@]} # Works out the length of path
let "last_ind -= 1" # Sets last_ind to index of script name
len_path=${path[@]:0:last_ind} # Gets the path without the script name
let "len_path=${#len_path[0]} + 1" # This gives the length of the script
string upto just before the last /
cd ${script[@]:0:len_path} # cds to the path
python script


As pretty much my first non-trivial bash script it's probably horrible but
it seems to work.

HTH,
Adam.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/f267ed5f/attachment.html>

From zstumgoren at gmail.com  Wed Jul 14 20:11:44 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Wed, 14 Jul 2010 14:11:44 -0400
Subject: [Tutor] Global name not found, though clearly in use
In-Reply-To: <i1krma$pv2$1@dough.gmane.org>
References: <4C3DE6BD.3000703@aim.com>
	<i1krma$pv2$1@dough.gmane.org>
Message-ID: <AANLkTikUbJtJnPs043dbZE8Sd3v-4zboHU5LkZDVln4H@mail.gmail.com>

>  Hmm..If I add a few debugging lines like that into my code, I get this:
>>
>
> The point was that statements in a class at class level (ie, not in defs)
> are executed sequentially and expect referenced variables to exist (ie,
> defined somewhere 'above' the current statement) -- there is no forward
> peeking going on.  Statements within def's (think 'deferred execution' if it
> helps) expect that the variables referred to will exist by the time the def
> is invoked.
>
> Python executes code top to bottom.  def's create an executable object and
> defers execution until invoked.  Other statements execute when encountered.
>  The statements in your class that start
>
>
Aside from other scattered problems with the code, Emile's explanation seems
to get at the core of the OP's confusion. But I was wondering (for my own
edification), can anyone point to the portion of the docs that clearly
spells out the order of execution (top to bottom, classes vs. functions,
etc.). The only place I've encountered such a discussion of execution order
was in Chapter 2 of Pro Django, and the below doc pages don't seem to
address the issue head-on (unless I'm misunderstanding or missed something):

http://docs.python.org/tutorial/classes.html
http://docs.python.org/reference/executionmodel.html

Thanks!
Serdar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/98751dda/attachment.html>

From emylistsddg at gmail.com  Wed Jul 14 20:35:02 2010
From: emylistsddg at gmail.com (eMyListsDDg)
Date: Wed, 14 Jul 2010 11:35:02 -0700
Subject: [Tutor] str format conversion help
In-Reply-To: <AANLkTimk9DtHlyhU7z4WbNoJDaeW3FK3ErFuu1fHtjir@mail.gmail.com>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
	<AANLkTimk9DtHlyhU7z4WbNoJDaeW3FK3ErFuu1fHtjir@mail.gmail.com>
Message-ID: <1237428025.20100714113502@gmail.com>


'\x00\x11\xb2\x00@,O\xa4'


the above str is being returned from one key/value pair in a dictionary. it is the addr of a network device.


i want to store the addr's in their 8byte mac format like this,

    [00 11 b2 00 40 2C 4F A4]

the combinations of format strings using the print statement hasn't resulted in what i need.


looking for a suggestion on how to format this, '\x00\x11\xb2\x00@,O\xa4' into this [00-11-B2-00-40-2C-4F-A4]


tia
 
Best regards,
 eMyListsDDg                            mailto:eMyListsDDg at gmail.com


From steve at alchemy.com  Wed Jul 14 20:39:33 2010
From: steve at alchemy.com (Steve Willoughby)
Date: Wed, 14 Jul 2010 11:39:33 -0700
Subject: [Tutor] str format conversion help
In-Reply-To: <1237428025.20100714113502@gmail.com>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>	<AANLkTimk9DtHlyhU7z4WbNoJDaeW3FK3ErFuu1fHtjir@mail.gmail.com>
	<1237428025.20100714113502@gmail.com>
Message-ID: <4C3E0465.4090402@alchemy.com>

On 14-Jul-10 11:35, eMyListsDDg wrote:
>
> '\x00\x11\xb2\x00@,O\xa4'
>
>
> the above str is being returned from one key/value pair in a dictionary. it is the addr of a network device.
>
>
> i want to store the addr's in their 8byte mac format like this,
>
>      [00 11 b2 00 40 2C 4F A4]
>
> the combinations of format strings using the print statement hasn't resulted in what i need.

A few hints:

Remember that the string is a set of raw binary values, so using ord() 
on each character would give you the numbers you can then have 
str.format() render as hex values.

You might also find the struct module helpful.

>
> looking for a suggestion on how to format this, '\x00\x11\xb2\x00@,O\xa4' into this [00-11-B2-00-40-2C-4F-A4]
>
>
> tia
>
> Best regards,
>   eMyListsDDg                            mailto:eMyListsDDg at gmail.com
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From ehamiter at gmail.com  Wed Jul 14 21:05:43 2010
From: ehamiter at gmail.com (Eric Hamiter)
Date: Wed, 14 Jul 2010 14:05:43 -0500
Subject: [Tutor] Searching a text file's contents and comparing them toa
	list
In-Reply-To: <AANLkTinQlMRNaLoVxCsXEBl6Lw0zALJzH3sFoF4TNc0Q@mail.gmail.com>
References: <AANLkTilsE1A5hTbLHDgCK1c91DS43WhOGVp1DcKUmDPx@mail.gmail.com> 
	<i1kn65$90i$1@dough.gmane.org>
	<AANLkTinlo6pCcoELrtWx7zthacfxSZHELZRVPcEX9eI-@mail.gmail.com> 
	<i1ks0u$r5j$1@dough.gmane.org>
	<AANLkTinQlMRNaLoVxCsXEBl6Lw0zALJzH3sFoF4TNc0Q@mail.gmail.com>
Message-ID: <AANLkTiklfp9uNmOZGqEx-R2SqeMvr0fIB8y0S8eBFKo7@mail.gmail.com>

Follow-up question: My code is now this:

aisle_one = ["chips", "bread", "pretzels", "magazines"]
aisle_two = ["juice", "ice cream"]
aisle_three = ["asparagus"]

def find_groceries():
    grocery_list = open("grocery_list.txt", "r")
    for line in grocery_list.readlines():
        line = line.strip()
        if line in aisle_one:
            first_run = "%s" % line + " - aisle one.\n"
        elif line in aisle_two:
            second_run = "%s" % line + " - aisle two.\n"
        elif line in aisle_three:
            third_run = "%s" % line + " - aisle three.\n"
        else:
            out_of_luck = "%s" % line
    print first_run, second_run, third_run
    print "I couldn't find any %s. Add it to the database. \n" % out_of_luck
    grocery_list.close()

find_groceries()


I can see that the variables first_run, second_run and third_run are
writing over themselves while looping, which is logical, but this is
not what I want. If I simply print them immediately instead of storing
them as variables, all items will print, but not in the order I wish.
The ultimate goal of the program will be to sort the items based on
aisle locations. Is there an efficient way to do this?

I think I want some kind of incremental counter going on in the loop
to prevent them from overwriting themselves, or a way to store
multiple variables, but I'm not sure how to do that.

Thanks for any ideas. This list and all its participants are super
helpful-- I'm very appreciative.

Eric

From rabidpoobear at gmail.com  Wed Jul 14 21:23:19 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 14 Jul 2010 14:23:19 -0500
Subject: [Tutor] Searching a text file's contents and comparing them toa
	list
In-Reply-To: <AANLkTiklfp9uNmOZGqEx-R2SqeMvr0fIB8y0S8eBFKo7@mail.gmail.com>
References: <AANLkTilsE1A5hTbLHDgCK1c91DS43WhOGVp1DcKUmDPx@mail.gmail.com>
	<i1kn65$90i$1@dough.gmane.org>
	<AANLkTinlo6pCcoELrtWx7zthacfxSZHELZRVPcEX9eI-@mail.gmail.com>
	<i1ks0u$r5j$1@dough.gmane.org>
	<AANLkTinQlMRNaLoVxCsXEBl6Lw0zALJzH3sFoF4TNc0Q@mail.gmail.com>
	<AANLkTiklfp9uNmOZGqEx-R2SqeMvr0fIB8y0S8eBFKo7@mail.gmail.com>
Message-ID: <6A57D127-6103-45A7-980D-3C17DE8FECB7@gmail.com>

You already know how to store multiple vars -- use lists! Just create a blank one before your loop and append() to it. Also you might think of a generic way to do this without relying on separate variables for each aisle, what if your store has 30 aisles? Hint: lists can contain any python object, even other lists.

Sent from my iPhone

On Jul 14, 2010, at 2:05 PM, Eric Hamiter <ehamiter at gmail.com> wrote:

> Follow-up question: My code is now this:
> 
> aisle_one = ["chips", "bread", "pretzels", "magazines"]
> aisle_two = ["juice", "ice cream"]
> aisle_three = ["asparagus"]
> 
> def find_groceries():
>    grocery_list = open("grocery_list.txt", "r")
>    for line in grocery_list.readlines():
>        line = line.strip()
>        if line in aisle_one:
>            first_run = "%s" % line + " - aisle one.\n"
>        elif line in aisle_two:
>            second_run = "%s" % line + " - aisle two.\n"
>        elif line in aisle_three:
>            third_run = "%s" % line + " - aisle three.\n"
>        else:
>            out_of_luck = "%s" % line
>    print first_run, second_run, third_run
>    print "I couldn't find any %s. Add it to the database. \n" % out_of_luck
>    grocery_list.close()
> 
> find_groceries()
> 
> 
> I can see that the variables first_run, second_run and third_run are
> writing over themselves while looping, which is logical, but this is
> not what I want. If I simply print them immediately instead of storing
> them as variables, all items will print, but not in the order I wish.
> The ultimate goal of the program will be to sort the items based on
> aisle locations. Is there an efficient way to do this?
> 
> I think I want some kind of incremental counter going on in the loop
> to prevent them from overwriting themselves, or a way to store
> multiple variables, but I'm not sure how to do that.
> 
> Thanks for any ideas. This list and all its participants are super
> helpful-- I'm very appreciative.
> 
> Eric
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From alan.gauld at btinternet.com  Wed Jul 14 21:27:00 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Jul 2010 20:27:00 +0100
Subject: [Tutor] str format conversion help
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com><AANLkTimk9DtHlyhU7z4WbNoJDaeW3FK3ErFuu1fHtjir@mail.gmail.com>
	<1237428025.20100714113502@gmail.com>
Message-ID: <i1l322$l5r$1@dough.gmane.org>


"eMyListsDDg" <emylistsddg at gmail.com> wrote 

First please start new threads wirth a new email, do not reply to 
a previous post - it confuses threaded readers. (and sometimes 
human readers too!)

> '\x00\x11\xb2\x00@,O\xa4'
> 
> the above str is being returned from one key/value pair in 
> a dictionary. it is the addr of a network device.
> 
> i want to store the addr's in their 8byte mac format like this,
> 
>    [00 11 b2 00 40 2C 4F A4]

Thats what you've got. The string is merely a representation 
of that data.

> the combinations of format strings using the print statement 
> hasn't resulted in what i need.

format strings are used to display data not to store it.
Do you really want to display the data in the format you've 
shown? Or do you really want to store it as 8 bytes?

The two concepts are completely different and more 
or less unrelated.

> looking for a suggestion on how to format this, 
> '\x00\x11\xb2\x00@,O\xa4' into this [00-11-B2-00-40-2C-4F-A4]

OK, to display it you need to extract each byte and convert it to 
a string representing the hex value. Fortunately you an treat a 
string of bytes as charactrers and the hex() function will give you 
the hex representation. So...

print "[%s]" % ('-'.join([hex(v) for v in theValue]) )

should be close...

HTH,


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



From alan.gauld at btinternet.com  Wed Jul 14 21:32:10 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Jul 2010 20:32:10 +0100
Subject: [Tutor] Searching a text file's contents and comparing them
	toalist
References: <AANLkTilsE1A5hTbLHDgCK1c91DS43WhOGVp1DcKUmDPx@mail.gmail.com>
	<i1kn65$90i$1@dough.gmane.org><AANLkTinlo6pCcoELrtWx7zthacfxSZHELZRVPcEX9eI-@mail.gmail.com>
	<i1ks0u$r5j$1@dough.gmane.org><AANLkTinQlMRNaLoVxCsXEBl6Lw0zALJzH3sFoF4TNc0Q@mail.gmail.com>
	<AANLkTiklfp9uNmOZGqEx-R2SqeMvr0fIB8y0S8eBFKo7@mail.gmail.com>
Message-ID: <i1l3bo$m9h$1@dough.gmane.org>


"Eric Hamiter" <ehamiter at gmail.com> wrote

> aisle_one = ["chips", "bread", "pretzels", "magazines"]
> aisle_two = ["juice", "ice cream"]
> aisle_three = ["asparagus"]
>
> def find_groceries():
>    grocery_list = open("grocery_list.txt", "r")
>    for line in grocery_list.readlines():

See previous about removing the redundant readlines()

>        line = line.strip()
>        if line in aisle_one:
>            first_run = "%s" % line + " - aisle one.\n"

The string formatting is redundant here since you assign a string to a 
string
You could just dio:

            first_run = line + " - aisle one.\n"

> I can see that the variables first_run, second_run and third_run are
> writing over themselves while looping, which is logical, but this is
> not what I want. If I simply print them immediately instead of 
> storing
> them as variables, all items will print, but not in the order I 
> wish.

So store the strings in a list then at the end print each list of 
strings.

> The ultimate goal of the program will be to sort the items based on
> aisle locations. Is there an efficient way to do this?

You can sort the lists before printing...

> I think I want some kind of incremental counter going on in the loop
> to prevent them from overwriting themselves, or a way to store
> multiple variables, but I'm not sure how to do that.

No need for counters, just append() to a list.


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



From emile at fenx.com  Wed Jul 14 22:37:42 2010
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 14 Jul 2010 13:37:42 -0700
Subject: [Tutor] Global name not found, though clearly in use
In-Reply-To: <AANLkTikUbJtJnPs043dbZE8Sd3v-4zboHU5LkZDVln4H@mail.gmail.com>
References: <4C3DE6BD.3000703@aim.com>	<i1krma$pv2$1@dough.gmane.org>
	<AANLkTikUbJtJnPs043dbZE8Sd3v-4zboHU5LkZDVln4H@mail.gmail.com>
Message-ID: <i1l79c$3o7$1@dough.gmane.org>

On 7/14/2010 11:11 AM Serdar Tumgoren said...
>But I was wondering (for my own
> edification), can anyone point to the portion of the docs that clearly
> spells out the order of execution (top to bottom, classes vs. functions,
> etc.).

I found this in the tutorial in the modules section:
   ( see http://docs.python.org/tutorial/modules.html )

    "A module is a file containing Python definitions and statements."

Ergo, stuff that executes and stuff that defines.

Further clarification provided:
"""A module can contain executable statements as well as function 
definitions. These statements are intended to initialize the module. 
They are executed only the first time the module is imported somewhere."""

... and a Footnote:
"""In fact function definitions are also statements that are executed; 
the execution of a module-level function enters the function name in the 
modules global symbol table."""

The same applies to the class namespaces created and the contained defs.

As to the execution order, that's apparently buried in the c sources of 
the scanner and tokenizer bits.  I didn't see anything more specific 
than "stream processing" and "*file" pointers hinting at serial 
processing of the source py file.


I also found this interesting (but possibly not to newbies :) :
   http://www.shinetech.com/attachments/108_python-language-internals.pdf

Emile


From ehamiter at gmail.com  Wed Jul 14 22:57:57 2010
From: ehamiter at gmail.com (Eric Hamiter)
Date: Wed, 14 Jul 2010 15:57:57 -0500
Subject: [Tutor] Searching a text file's contents and comparing them
	toalist
In-Reply-To: <i1l3bo$m9h$1@dough.gmane.org>
References: <AANLkTilsE1A5hTbLHDgCK1c91DS43WhOGVp1DcKUmDPx@mail.gmail.com> 
	<i1kn65$90i$1@dough.gmane.org>
	<AANLkTinlo6pCcoELrtWx7zthacfxSZHELZRVPcEX9eI-@mail.gmail.com> 
	<i1ks0u$r5j$1@dough.gmane.org>
	<AANLkTinQlMRNaLoVxCsXEBl6Lw0zALJzH3sFoF4TNc0Q@mail.gmail.com> 
	<AANLkTiklfp9uNmOZGqEx-R2SqeMvr0fIB8y0S8eBFKo7@mail.gmail.com> 
	<i1l3bo$m9h$1@dough.gmane.org>
Message-ID: <AANLkTilY91KVJXgSDKJqCQ92IDxATPyoUfzOJHh2mozE@mail.gmail.com>

Thanks for the pointers! This is now working, albeit probably ugly and clunky:


aisle_one = ["chips", "bread", "pretzels", "magazines"]
aisle_two = ["juice", "ice cream"]
aisle_three = ["asparagus"]

def find_groceries():
    with open("grocery_list.txt") as grocery_list:

        first_trip = ["Located on aisle 1: "]
        second_trip = ["Located on aisle 2: "]
        third_trip = ["Located on aisle 3: "]
        no_trip = ["Not found in the database: "]

        for item in grocery_list:
            item = item.rstrip()
            if item in aisle_one:
                first_trip.append(item)
            elif item in aisle_two:
                second_trip.append(item)
            elif item in aisle_three:
                third_trip.append(item)
            else:
                no_trip.append(item)

    sorted_list = first_trip, second_trip, third_trip, no_trip
    print sorted_list

find_groceries()


Last question (for today, at least): Right now, the output is less
than aesthetically pleasing:

(['Located on aisle 1: ', 'bread', 'magazines'], ['Located on aisle 2:
', 'juice', 'ice cream'], ['Located on aisle 3: ', 'asparagus'], ['Not
found in the database: ', 'butter', 'soap'])

How can I format it so it looks more like this:

Located on aisle 1:
bread
magazines

Located on aisle 2
[etc...]


I tried putting "\n" into it but it just prints the literal string.
I'm sure it has to do with the list format of holding multiple items,
but so far haven't found a way to break them apart.

Thanks,

Eric

From davidheiserca at gmail.com  Wed Jul 14 23:03:27 2010
From: davidheiserca at gmail.com (davidheiserca at gmail.com)
Date: Wed, 14 Jul 2010 14:03:27 -0700
Subject: [Tutor] Searching a text file's contents and comparing them to
	alist
References: <AANLkTilsE1A5hTbLHDgCK1c91DS43WhOGVp1DcKUmDPx@mail.gmail.com>
Message-ID: <1B6A1398518F407F8491EC7309F377B1@dheiser>


There are probably "return" characters at the end of each "line" from the 
"grocery_list".

Try using the String method "line.strip()".

Or "grocery_list.read().splitlines()"




----- Original Message ----- 
From: "Eric Hamiter" <ehamiter at gmail.com>
To: <tutor at python.org>
Sent: Wednesday, July 14, 2010 8:46 AM
Subject: [Tutor] Searching a text file's contents and comparing them to 
alist


> Hi all,
>
> New programmer here. This is what I want to do:
>
> 1. Open an existing text file named "grocery_list.txt", which has one
> item per line, like so:
>
> butter
> juice
> bread
> asparagus
> magazines
> ice cream
>
> 2. ...and search for these items in a pre-defined list.
>
> But I can't seem to get this working. Right now after trying the 
> following:
>
>
> aisle_one = ["chips", "bread", "pretzels", "magazines"]
>
> grocery_list = open("grocery_list.txt", "r")
> for line in grocery_list.readlines():
>    if line in aisle_one:
>       print "success"
>    else:
>       print "no joy"
> grocery_list.close()
>
>
> I get this:
>
> no joy
> no joy
> no joy
> no joy
> no joy
> no joy
>
> when I'm expecting this:
>
> no joy
> no joy
> success
> no joy
> success
> no joy
>
>
> Am I close? This seems like it should work but I'm obviously missing 
> something.
>
> Thanks,
>
> Eric
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor 


From zstumgoren at gmail.com  Wed Jul 14 23:24:01 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Wed, 14 Jul 2010 17:24:01 -0400
Subject: [Tutor] Global name not found, though clearly in use
In-Reply-To: <i1l79c$3o7$1@dough.gmane.org>
References: <4C3DE6BD.3000703@aim.com> <i1krma$pv2$1@dough.gmane.org>
	<AANLkTikUbJtJnPs043dbZE8Sd3v-4zboHU5LkZDVln4H@mail.gmail.com>
	<i1l79c$3o7$1@dough.gmane.org>
Message-ID: <AANLkTimqATkzTC9H93BlkVryxC97Tffpg3WQvkGzTyqm@mail.gmail.com>

>
>
>>
> I also found this interesting (but possibly not to newbies :) :
>  http://www.shinetech.com/attachments/108_python-language-internals.pdf
>
> Very helpful, especially that last resource. Thank you!

Serdar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/f4585f56/attachment.html>

From christopher.henk at allisontransmission.com  Thu Jul 15 00:12:37 2010
From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com)
Date: Wed, 14 Jul 2010 18:12:37 -0400
Subject: [Tutor] Searching a text file's contents and comparing
	them	toalist
In-Reply-To: <AANLkTilY91KVJXgSDKJqCQ92IDxATPyoUfzOJHh2mozE@mail.gmail.com>
Message-ID: <OF31433DDA.14770628-ON85257760.0077F0B0-85257760.007A0920@mail.ati.int>

Eric Hamiter wrote on 07/14/2010 04:57:57 PM:

> Thanks for the pointers! This is now working, albeit probably ugly and 
clunky:
> 
> 
> aisle_one = ["chips", "bread", "pretzels", "magazines"]
> aisle_two = ["juice", "ice cream"]
> aisle_three = ["asparagus"]
> 
> def find_groceries():
>     with open("grocery_list.txt") as grocery_list:
> 
>         first_trip = ["Located on aisle 1: "]
>         second_trip = ["Located on aisle 2: "]
>         third_trip = ["Located on aisle 3: "]
>         no_trip = ["Not found in the database: "]
> 
>         for item in grocery_list:
>             item = item.rstrip()
>             if item in aisle_one:
>                 first_trip.append(item)
>             elif item in aisle_two:
>                 second_trip.append(item)
>             elif item in aisle_three:
>                 third_trip.append(item)
>             else:
>                 no_trip.append(item)
> 
>     sorted_list = first_trip, second_trip, third_trip, no_trip
>     print sorted_list
> 
> find_groceries()
> 
> 
> Last question (for today, at least): Right now, the output is less
> than aesthetically pleasing:
> 
> (['Located on aisle 1: ', 'bread', 'magazines'], ['Located on aisle 2:
> ', 'juice', 'ice cream'], ['Located on aisle 3: ', 'asparagus'], ['Not
> found in the database: ', 'butter', 'soap'])
> 
> How can I format it so it looks more like this:
> 
> Located on aisle 1:
> bread
> magazines
> 
> Located on aisle 2
> [etc...]
> 
> 
> I tried putting "\n" into it but it just prints the literal string.
> I'm sure it has to do with the list format of holding multiple items,
> but so far haven't found a way to break them apart.
> 


your sorted_list is a tuple of lists so when you print it python is 
showing you that structure.
You want the contents of each of those lists printed in a more readable 
format, so you need to loop through the tuple to get each list(trips down 
an aisle)and then within that loop, loop through each list to print each 
item.

in pseudo code to output like you suggest

for each aisle_list in sorted_list
        for each item in the aisle_list
                print the item
        print the space (to separate the aisles, this is part of the loop 
through the tuple, so will run once for each aisle)


Instead of replacing the print statement with the above, I would have this 
as another function which takes sorted_list as a parameter, changing 
find_groceries to return sorted_list instead of printing it.  This keeps 
the two tasks separate and easier to understand and/or debug.

so the last lines of your program are:
sorted_list=find_groceries()
print_shoppinglist(sorted_list)

instead of just calling find_groceries()


Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/86f262cf/attachment.html>

From airscorp at otenet.gr  Thu Jul 15 01:26:24 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Thu, 15 Jul 2010 02:26:24 +0300
Subject: [Tutor] Searching a text file's contents and comparing
	them	toalist
In-Reply-To: <AANLkTilY91KVJXgSDKJqCQ92IDxATPyoUfzOJHh2mozE@mail.gmail.com>
References: <AANLkTilsE1A5hTbLHDgCK1c91DS43WhOGVp1DcKUmDPx@mail.gmail.com>
	<i1kn65$90i$1@dough.gmane.org>	<AANLkTinlo6pCcoELrtWx7zthacfxSZHELZRVPcEX9eI-@mail.gmail.com>
	<i1ks0u$r5j$1@dough.gmane.org>	<AANLkTinQlMRNaLoVxCsXEBl6Lw0zALJzH3sFoF4TNc0Q@mail.gmail.com>
	<AANLkTiklfp9uNmOZGqEx-R2SqeMvr0fIB8y0S8eBFKo7@mail.gmail.com>
	<i1l3bo$m9h$1@dough.gmane.org>
	<AANLkTilY91KVJXgSDKJqCQ92IDxATPyoUfzOJHh2mozE@mail.gmail.com>
Message-ID: <4C3E47A0.5080202@otenet.gr>

On 07/14/2010 11:57 PM, Eric Hamiter wrote:
> Last question (for today, at least): Right now, the output is less
> than aesthetically pleasing:
>
> (['Located on aisle 1: ', 'bread', 'magazines'], ['Located on aisle 2:
> ', 'juice', 'ice cream'], ['Located on aisle 3: ', 'asparagus'], ['Not
> found in the database: ', 'butter', 'soap'])
>
> How can I format it so it looks more like this:
>
> Located on aisle 1:
> bread
> magazines
>
> Located on aisle 2
> [etc...]
>
>
> I tried putting "\n" into it but it just prints the literal string.
> I'm sure it has to do with the list format of holding multiple items,
> but so far haven't found a way to break them apart.
>
>
>    
Readup on str.join() 
http://docs.python.org/library/stdtypes.html#str.join (link is not that 
helpful I admit, google some uses too)
For example,
print "\n".join(first_run)
will get you started.

I think the end code you're looking for is something like

output = ["\n".join(run) for run in sorted_list]
print "\n".join(output)

but I'm not sure if you've got the hang of list comprehensions by now.

Nick

From bgailer at gmail.com  Thu Jul 15 03:53:45 2010
From: bgailer at gmail.com (bob gailer)
Date: Wed, 14 Jul 2010 21:53:45 -0400
Subject: [Tutor] Searching a text file's contents and comparing
	them	toalist
In-Reply-To: <AANLkTilY91KVJXgSDKJqCQ92IDxATPyoUfzOJHh2mozE@mail.gmail.com>
References: <AANLkTilsE1A5hTbLHDgCK1c91DS43WhOGVp1DcKUmDPx@mail.gmail.com>
	<i1kn65$90i$1@dough.gmane.org>	<AANLkTinlo6pCcoELrtWx7zthacfxSZHELZRVPcEX9eI-@mail.gmail.com>
	<i1ks0u$r5j$1@dough.gmane.org>	<AANLkTinQlMRNaLoVxCsXEBl6Lw0zALJzH3sFoF4TNc0Q@mail.gmail.com>
	<AANLkTiklfp9uNmOZGqEx-R2SqeMvr0fIB8y0S8eBFKo7@mail.gmail.com>
	<i1l3bo$m9h$1@dough.gmane.org>
	<AANLkTilY91KVJXgSDKJqCQ92IDxATPyoUfzOJHh2mozE@mail.gmail.com>
Message-ID: <4C3E6A29.3090906@gmail.com>

[snip]

Since you look up the items in the grocery list it seems to me a 
dictionary relating each item to its aisle would be best.

inventory = {"chips" : 1, "bread" : 1, "pretzels" : 1, "magazines" : 1,
              "juice" : 2, "ice cream" : 2,
              "asparagus" : 3}
MAX_AISLE = 3
aisles = [[] for i in range(MAX_AISLE)]
for item in grocery_list:
   aisle = inventory.get(item.strip(), MAX_AISLE)
   aisles[aisle-1].append(item)

To address the formatting question:

for aisleNo, items in enumerate(aisles):
   if aisleNo < MAX_AISLE - 1:
     print "Located on aisle %s" % aisleNo + 1
   else:
     print "Not in store"
   print "\n".join(items)


-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From emylistsddg at gmail.com  Thu Jul 15 05:08:45 2010
From: emylistsddg at gmail.com (eMyListsDDg)
Date: Wed, 14 Jul 2010 20:08:45 -0700
Subject: [Tutor] str format conversion help
In-Reply-To: <4C3E0465.4090402@alchemy.com>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
	<AANLkTimk9DtHlyhU7z4WbNoJDaeW3FK3ErFuu1fHtjir@mail.gmail.com>
	<1237428025.20100714113502@gmail.com>
	<4C3E0465.4090402@alchemy.com>
Message-ID: <761777369.20100714200845@gmail.com>

Steve,


glad you pointed that out. 

struct.unpack or something...i'll look into that module.

thx



> On 14-Jul-10 11:35, eMyListsDDg wrote:

>> '\x00\x11\xb2\x00@,O\xa4'


>> the above str is being returned from one key/value pair in a dictionary. it is the addr of a network device.


>> i want to store the addr's in their 8byte mac format like this,

>>      [00 11 b2 00 40 2C 4F A4]

>> the combinations of format strings using the print statement hasn't resulted in what i need.

> A few hints:

> Remember that the string is a set of raw binary values, so using ord() 
> on each character would give you the numbers you can then have 
> str.format() render as hex values.

> You might also find the struct module helpful.


>> looking for a suggestion on how to format this, '\x00\x11\xb2\x00@,O\xa4' into this [00-11-B2-00-40-2C-4F-A4]


>> tia

>> Best regards,
>>   eMyListsDDg                            mailto:eMyListsDDg at gmail.com

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

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



-- 
Best regards,
 eMyListsDDg                            mailto:eMyListsDDg at gmail.com


From emylistsddg at gmail.com  Thu Jul 15 05:15:55 2010
From: emylistsddg at gmail.com (eMyListsDDg)
Date: Wed, 14 Jul 2010 20:15:55 -0700
Subject: [Tutor] str format conversion help
In-Reply-To: <i1l322$l5r$1@dough.gmane.org>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com><AANLkTimk9DtHlyhU7z4WbNoJDaeW3FK3ErFuu1fHtjir@mail.gmail.com>
	<1237428025.20100714113502@gmail.com>
	<i1l322$l5r$1@dough.gmane.org>
Message-ID: <150456423.20100714201555@gmail.com>

Hello Alan,

> First please start new threads wirth a new email, do not reply to 

thought i did, my apologies.



> "eMyListsDDg" <emylistsddg at gmail.com> wrote 

> First please start new threads wirth a new email, do not reply to 
> a previous post - it confuses threaded readers. (and sometimes 
> human readers too!)

>> '\x00\x11\xb2\x00@,O\xa4'

>> the above str is being returned from one key/value pair in 
>> a dictionary. it is the addr of a network device.

>> i want to store the addr's in their 8byte mac format like this,

>>    [00 11 b2 00 40 2C 4F A4]

> Thats what you've got. The string is merely a representation 
> of that data.

>> the combinations of format strings using the print statement 
>> hasn't resulted in what i need.

> format strings are used to display data not to store it.
> Do you really want to display the data in the format you've 
> shown? Or do you really want to store it as 8 bytes?


the format shown. now that you point out a few things, it really wouldn't matter. 

> The two concepts are completely different and more 
> or less unrelated.

i see that now, as a newbie to python. 


>> looking for a suggestion on how to format this, 
>> '\x00\x11\xb2\x00@,O\xa4' into this [00-11-B2-00-40-2C-4F-A4]

> OK, to display it you need to extract each byte and convert it to 
> a string representing the hex value. Fortunately you an treat a 
> string of bytes as charactrers and the hex() function will give you 
> the hex representation. So...

> print "[%s]" % ('-'.join([hex(v) for v in theValue]) )

helps me to understand the concept differences you pointed out better

appreciate the help...



From memilanuk at gmail.com  Thu Jul 15 06:55:00 2010
From: memilanuk at gmail.com (Monte Milanuk)
Date: Wed, 14 Jul 2010 21:55:00 -0700
Subject: [Tutor] Handling 'None' (null) values when processing sqlite
	cursorresults
In-Reply-To: <i1kaol$ilg$1@dough.gmane.org>
References: <i1jeji$rho$1@dough.gmane.org> <i1kaol$ilg$1@dough.gmane.org>
Message-ID: <i1m4b4$ccv$1@dough.gmane.org>

On 7/14/10 5:32 AM, Alan Gauld wrote:

> The key principle is do not try to store your data in a display format.

Never was my intention.  I just hadn't anticipated needing to write my 
own function to handle something as (I would think) common as a NULL 
value in a database field.

I had been working with something very simple like:

for lines in cursor.fetchall()
	title = lines[1]
	first = lines[2]
	mid = lines[3]
	last = lines[4]
	...

	print "%s %s %s %s" % (title, first, mid, last)
	print "%s" % (street)
	print "%s, %s %s" % (city, state, zipcode)
	print "%s" % (phone)
	print "%s" % (email)

etc. etc.  for one format (supposed to look like a mailing label, more 
or less), and then I was going to experiment with other formatting later.

I'll work with the stuff you all have provided as I get time... thanks a 
bunch!

Monte


From cwitts at compuscan.co.za  Thu Jul 15 07:37:57 2010
From: cwitts at compuscan.co.za (Christian Witts)
Date: Thu, 15 Jul 2010 07:37:57 +0200
Subject: [Tutor] Handling 'None' (null) values when processing sqlite
 cursorresults
In-Reply-To: <i1ksg0$sv0$1@dough.gmane.org>
References: <i1jeji$rho$1@dough.gmane.org>
	<i1kaol$ilg$1@dough.gmane.org>	<4C3DB471.6030203@compuscan.co.za>
	<i1ksg0$sv0$1@dough.gmane.org>
Message-ID: <4C3E9EB5.6090100@compuscan.co.za>

On 14/07/2010 19:34, Alan Gauld wrote:
>
> "Christian Witts" <cwitts at compuscan.co.za> wrote
>
>>> You need a display function that can strip out the nulls as needed.
>>> A simple list comprehension or generator expression would work
>>> in this case:
>>     print ' '.join(str(field) for field in data if field is not 'None')
>>
>> The problem with that is if you're relying on a set delimiter you are 
>> removing elements so you would be better served by doing `str(field) 
>> if field != None else '' for field in record`
>
> True, although in this case we do seem to have a fixed condition
> since it's the database's representation of null but I originally didn't
> notice the quotes around None. When I fixed that I should have
> changed is to equals..
>
>>     print ' '.join(str(field) for field in data if field != 'None')
>
> But your modification confuses me. can you explain?
> What would the print line look like?
>
> Alan G.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

I prefer not to use a space delimiter, generally a pipe |, so the output 
would look a lot like
104||Sylvester||Evans||527-9210 Prion 
Av.|Liberal|VT|24742|1-135-197-1139|vehicula.Pellentesque at idmollis.edu|2010-07-13 
22:52:50|2010-07-13 22:52:50

The reason I suggested that usage instead is because Monte said
 >>> having the 'None' values omitted really messed with the list order 
which I was depending on

So if you're wanting to create a new list which removes the Nones but 
still keeps the same indexing it would be the way to do it, imho.

-- 
Kind Regards,
Christian Witts



From emylistsddg at gmail.com  Thu Jul 15 09:09:34 2010
From: emylistsddg at gmail.com (eMyListsDDg)
Date: Thu, 15 Jul 2010 00:09:34 -0700
Subject: [Tutor] str format conversion help
In-Reply-To: <AANLkTimsGdRm8gPdeJwJ1RxbdvMxhqDd_VBdV_xE8D2p@mail.gmail.com>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com>
	<AANLkTimk9DtHlyhU7z4WbNoJDaeW3FK3ErFuu1fHtjir@mail.gmail.com>
	<1237428025.20100714113502@gmail.com>
	<AANLkTimsGdRm8gPdeJwJ1RxbdvMxhqDd_VBdV_xE8D2p@mail.gmail.com>
Message-ID: <1829900426.20100715000934@gmail.com>

thanks,
   

def conv_tst(bytes)
	
     return ('-'.join([binascii.hexlify(v) for v in bytes]))



i ended up experimenting with the suggestions and the above returns what i'm looking for, i.e., the formatted mac addr to store in a sqlite db. 

i'm sure there are other ways, though the above is working now.



mucho gracias all




> use de fucntion encode. For example:

> '\x7e\x00\x20'.encode('hex') will return that = '7e0020'  



From alan.gauld at btinternet.com  Thu Jul 15 11:13:27 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Thu, 15 Jul 2010 09:13:27 +0000 (GMT)
Subject: [Tutor] str format conversion help
In-Reply-To: <150456423.20100714201555@gmail.com>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com><AANLkTimk9DtHlyhU7z4WbNoJDaeW3FK3ErFuu1fHtjir@mail.gmail.com>
	<1237428025.20100714113502@gmail.com>
	<i1l322$l5r$1@dough.gmane.org> <150456423.20100714201555@gmail.com>
Message-ID: <850361.23381.qm@web86701.mail.ird.yahoo.com>



> print "[%s]" % ('-'.join([hex(v) for v in  theValue]) )

Oops, that leaves 0x at the front of each byte.

You could strip that off with

print "[%s]" % ('-'.join([hex(v)[2:] for v in  theValue]) )

Sorry,

Alan G.

From payal-python at scriptkitchen.com  Thu Jul 15 14:09:24 2010
From: payal-python at scriptkitchen.com (Payal)
Date: Thu, 15 Jul 2010 05:09:24 -0700
Subject: [Tutor] Request for help learning the right way to deal
	with	listsin lists
In-Reply-To: <i1h50d$4vu$1@dough.gmane.org>
References: <mailman.2673.1278948588.1671.tutor@python.org>
	<359328.83032.qm@web44711.mail.sp1.yahoo.com>
	<i1h50d$4vu$1@dough.gmane.org>
Message-ID: <20100715120924.GA25972@scriptkitchen.com>

On Tue, Jul 13, 2010 at 08:35:45AM +0100, Alan Gauld wrote:
> If the data gets more complex you could put the data into a class:
>
> class Book:
>      def __init__(self, title, pages=[]):
>          self.title = title
>          self.pages = pages
>
> Books = [ Book('War & Peace", [3,56,88]),
>               Book("Huck Finn", [2,5,19]) ]

Can someone please explain the above 2 lines?

> for book in Books:
>     print book.title, book.pages

With warm regards,
-Payal
-- 

From marris1031 at gmail.com  Thu Jul 15 17:03:53 2010
From: marris1031 at gmail.com (Mary Morris)
Date: Thu, 15 Jul 2010 09:03:53 -0600
Subject: [Tutor] Parsing through decorators program
Message-ID: <AANLkTilUP71fmbZTjGg1EKD-JmiM4mqvUk7zKCdp7vvo@mail.gmail.com>

So my new internship asked me to write a program that would parse through
all of our source code on an svn server, find all the decorators and print
them. I found all of the decorators by finding the '@' symbol.  What I still
have to do is write something that will make the computer print all of the
names of the decorators that it finds.  So far, this is what I have written:

# Written by Mary Morris
# July 2010
#





import os
import warnings
import traceback





##
#
#
def get_py_files(path):
ret = []
 if path[-1] != '/':
path += '/'
 files = os.listdir(path)
for file in files:
if file == '.svn':
continue
 if os.path.isdir(path + file + '/'):
temp = get_py_files(path + file + '/')
for ele in temp:
ret.append(ele)
 else:
ext = file.split('.')[-1]
if ext != 'py':
continue
 temp = path + file
temp = temp.replace('/', '\\')
 ret.append(temp)
 return ret










if __name__ == '__main__':
imports = {}
 files = get_py_files(os.getcwd())
 our_modules = [file.split('\\')[-1][:-3] for file in files]
 for file in files:
# for file in files[:1]:
f = open(file)
lines = f.readlines()
f.close()
 for line in lines:
line = line[:-1]
 #
# Conveniently, "import bleh" and "from bleh import bleh2" both have the
second string (when split) of "bleh"
#
if line.startswith('import') or line.startswith('from'):
line = line.replace('\t', ' ')
temp = [s for s in line.split(' ') if len(s) != 0]
 # This is because FirstAssist uses "import os, sys" (and similar) all over
the place...
if temp[1].find('@') != -1:
for ele in temp[1:]:
ele = ele.replace('@', '')
if not ele in imports.keys():
# imports[ele] = [file.split('\\')[-1]]
imports[ele] = [file]
else:
# imports[ele] += [file.split('\\')[-1]]
imports[ele] += [file]
else:
if not temp[1] in imports.keys():
# imports[temp[1]] = [file.split('\\')[-1]]
imports[temp[1]] = [file]
else:
# imports[temp[1]] += [file.split('\\')[-1]]
imports[temp[1]] += [file]
  external_imports = [im for im in imports.keys() if not im in our_modules]
 dependencies = []



Could you give me suggestions on how to make my program print the names of
the decorators?
Thanks,
Mary
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100715/056d3faf/attachment.html>

From jf_byrnes at comcast.net  Thu Jul 15 18:21:26 2010
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Thu, 15 Jul 2010 11:21:26 -0500
Subject: [Tutor] Path?
In-Reply-To: <AANLkTimNfk56PblsqqfM_RxlRViWGQd7RX2WGMxxxmHT@mail.gmail.com>
References: <4C3A0284.6090901@comcast.net>
	<201007120932.06800.steve@pearwood.info>
	<4C3C6D8C.4090202@comcast.net>
	<AANLkTikF2HzyOLTymwAjcWxr7KPiSNVuQyIhB07DtS_s@mail.gmail.com>
	<4C3CE854.5060803@comcast.net>
	<AANLkTik6FcbxVzajVr5HDOrG3j5EaJbRk8Uv7SnbQT6k@mail.gmail.com>
	<4C3D1884.8070501@comcast.net>
	<AANLkTikN4PhkIhIYJC3KuPUmteAeGXumnXy7kzcgUkRL@mail.gmail.com>
	<4C3DE8B2.7000206@comcast.net>
	<AANLkTimNfk56PblsqqfM_RxlRViWGQd7RX2WGMxxxmHT@mail.gmail.com>
Message-ID: <4C3F3586.5000103@comcast.net>

Adam Bark wrote:
> On 14 July 2010 17:41, Jim Byrnes<jf_byrnes at comcast.net>  wrote:
>
>> Adam Bark wrote:
>>
>>> On 14 July 2010 02:53, Jim Byrnes<jf_byrnes at comcast.net>   wrote:
>>>
>>>   Adam Bark wrote:
>>>>
>>>> <snipped some old stuff>
>>>>
>>>>
>>>>   If I use the terminal to start the program it has no problem using the
>>>>
>>>>>   file.  There are multiple files in multiple directories so I was
>>>>>>>> looking
>>>>>>>> for
>>>>>>>> a way to just double click them and have them run.  If it turns out
>>>>>>>> that
>>>>>>>> I
>>>>>>>> must make changes to or for each of the files it will be easier to
>>>>>>>> just
>>>>>>>> keep
>>>>>>>> using the terminal.  I've only been using Ubuntu for a few months so
>>>>>>>> I
>>>>>>>> was
>>>>>>>> surprised that the program could not see a file that is in the same
>>>>>>>> directory.
>>>>>>>>
>>>>>>>> Regards,  Jim
>>>>>>>>
>>>>>>>>
>>>>>>>>
>>>>>>> The problem is ubuntu doesn't run the script from the directory it's
>>>>>>> in
>>>>>>> so
>>>>>>> it's looking for wxPython.jpg somewhere else.
>>>>>>>
>>>>>>>
>>>>>>>   OK, I mistakenly thought that double-clicking on file in Nautilus
>>>>>>> would
>>>>>>>
>>>>>> take care of the path info.
>>>>>>
>>>>>> In my reply above I also mentioned that I tried by dropping it on a
>>>>>> Launcher on the top panel and that the command the launcher uses is
>>>>>> usr/bin/python2.6.  Is there a way that the command can be changed so
>>>>>> that
>>>>>> it will look in the same directory the python script is in for any file
>>>>>> it
>>>>>> needs?
>>>>>>
>>>>>> Thanks,  Jim
>>>>>>
>>>>>>
>>>>>
>>>>> Not sure if you got my previous email but you could try writing the bash
>>>>> script I posted (with the $1 line to get the path) and setting that as
>>>>> your
>>>>> launcher, I think it should work.
>>>>>
>>>>> Let me know if you didn't get it or it doesn't work.
>>>>>
>>>>> HTH,
>>>>> Adam.
>>>>>
>>>>>
>>>>>   I got it, got sidetracked and then forgot to look at it again.  Thanks
>>>> for
>>>> reminding me.  Your idea works, but with one little downside.  The
>>>> directories I am working with are chapters in a book.  So as I move from
>>>> chapter to chapter I will need to change the bash script, but this seems
>>>> to
>>>> be less typing than using the terminal.
>>>>
>>>>
>>>> Thanks,  Jim
>>>>
>>>>
>>> Ok cool, glad it works. It might be possible to get the path so you don't
>>> have to set it each time, try this:
>>>
>>> #!/bin/bash
>>> IFS="/"
>>> path=($1)
>>> cd $(path[0:#path[*]])
>>> python $1
>>>
>>>
>>> # Warning, I'm not exactly a competent bash programmer so this may not
>>> work
>>> :-p
>>>
>>> Let me know if you need a hand to fix it,
>>>
>>> HTH,
>>> Adam.
>>>
>>>
>> I tried the new bash code but when I dropped a file on the launcher it just
>> flashed an gave no output.  So I tried running the bash script
>> (name=runpython) in a terminal and got this error:
>>
>> /home/jfb/runpython: line 4: path[0:#path[*]]: command not found
>> Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
>> [GCC 4.4.3] on linux2
>> Type "help", "copyright", "credits" or "license" for more information.
>>>>>
>>
>> I know even less about bash than you do, so I don't where to start to debug
>> this.
>>
>>
>> Thanks,  Jim
>>
>> Ok then, this time it's tested and not just improvised, here we go:
>
> #!/bin/bash
>
> script=$1 # Full path for calling the script later
> orig_IFS=$IFS # This is to reset IFS so that "script" is correct (otherwise
> has spaces instead of /)
> IFS="/"
> path=( $1 )
> IFS=$orig_IFS
> last_ind=${#path[@]} # Works out the length of path
> let "last_ind -= 1" # Sets last_ind to index of script name
> len_path=${path[@]:0:last_ind} # Gets the path without the script name
> let "len_path=${#len_path[0]} + 1" # This gives the length of the script
> string upto just before the last /
> cd ${script[@]:0:len_path} # cds to the path
> python script
>
>
> As pretty much my first non-trivial bash script it's probably horrible but
> it seems to work.
>
> HTH,
> Adam.
>

There must be something different in our setups because it did not work 
for me.  If I run it from a terminal I get:

jfb at jfb-ubuntu64:~$ /home/jfb/runpython_test bitmap_button.py
/home/jfb/runpython_test: line 12: cd: b: No such file or directory
python: can't open file 'script': [Errno 2] No such file or directory
jfb at jfb-ubuntu64:~$

Thanks  Jim


From adam.jtm30 at gmail.com  Thu Jul 15 18:29:02 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Thu, 15 Jul 2010 17:29:02 +0100
Subject: [Tutor] Path?
In-Reply-To: <4C3F3586.5000103@comcast.net>
References: <4C3A0284.6090901@comcast.net>
	<201007120932.06800.steve@pearwood.info> 
	<4C3C6D8C.4090202@comcast.net>
	<AANLkTikF2HzyOLTymwAjcWxr7KPiSNVuQyIhB07DtS_s@mail.gmail.com> 
	<4C3CE854.5060803@comcast.net>
	<AANLkTik6FcbxVzajVr5HDOrG3j5EaJbRk8Uv7SnbQT6k@mail.gmail.com> 
	<4C3D1884.8070501@comcast.net>
	<AANLkTikN4PhkIhIYJC3KuPUmteAeGXumnXy7kzcgUkRL@mail.gmail.com> 
	<4C3DE8B2.7000206@comcast.net>
	<AANLkTimNfk56PblsqqfM_RxlRViWGQd7RX2WGMxxxmHT@mail.gmail.com> 
	<4C3F3586.5000103@comcast.net>
Message-ID: <AANLkTik5tnZCY-cO-LWDTD9Gnvr0_TVhkDn_joNnbncZ@mail.gmail.com>

On 15 July 2010 17:21, Jim Byrnes <jf_byrnes at comcast.net> wrote:

> Adam Bark wrote:
>
>> On 14 July 2010 17:41, Jim Byrnes<jf_byrnes at comcast.net>  wrote:
>>
>>  Adam Bark wrote:
>>>
>>>  On 14 July 2010 02:53, Jim Byrnes<jf_byrnes at comcast.net>   wrote:
>>>>
>>>>  Adam Bark wrote:
>>>>
>>>>>
>>>>> <snipped some old stuff>
>>>>>
>>>>>
>>>>>  If I use the terminal to start the program it has no problem using the
>>>>>
>>>>>   file.  There are multiple files in multiple directories so I was
>>>>>>
>>>>>>>  looking
>>>>>>>>> for
>>>>>>>>> a way to just double click them and have them run.  If it turns out
>>>>>>>>> that
>>>>>>>>> I
>>>>>>>>> must make changes to or for each of the files it will be easier to
>>>>>>>>> just
>>>>>>>>> keep
>>>>>>>>> using the terminal.  I've only been using Ubuntu for a few months
>>>>>>>>> so
>>>>>>>>> I
>>>>>>>>> was
>>>>>>>>> surprised that the program could not see a file that is in the same
>>>>>>>>> directory.
>>>>>>>>>
>>>>>>>>> Regards,  Jim
>>>>>>>>>
>>>>>>>>>
>>>>>>>>>
>>>>>>>>>  The problem is ubuntu doesn't run the script from the directory
>>>>>>>> it's
>>>>>>>> in
>>>>>>>> so
>>>>>>>> it's looking for wxPython.jpg somewhere else.
>>>>>>>>
>>>>>>>>
>>>>>>>>  OK, I mistakenly thought that double-clicking on file in Nautilus
>>>>>>>> would
>>>>>>>>
>>>>>>>>  take care of the path info.
>>>>>>>
>>>>>>> In my reply above I also mentioned that I tried by dropping it on a
>>>>>>> Launcher on the top panel and that the command the launcher uses is
>>>>>>> usr/bin/python2.6.  Is there a way that the command can be changed so
>>>>>>> that
>>>>>>> it will look in the same directory the python script is in for any
>>>>>>> file
>>>>>>> it
>>>>>>> needs?
>>>>>>>
>>>>>>> Thanks,  Jim
>>>>>>>
>>>>>>>
>>>>>>>
>>>>>> Not sure if you got my previous email but you could try writing the
>>>>>> bash
>>>>>> script I posted (with the $1 line to get the path) and setting that as
>>>>>> your
>>>>>> launcher, I think it should work.
>>>>>>
>>>>>> Let me know if you didn't get it or it doesn't work.
>>>>>>
>>>>>> HTH,
>>>>>> Adam.
>>>>>>
>>>>>>
>>>>>>  I got it, got sidetracked and then forgot to look at it again.
>>>>>>  Thanks
>>>>>>
>>>>> for
>>>>> reminding me.  Your idea works, but with one little downside.  The
>>>>> directories I am working with are chapters in a book.  So as I move
>>>>> from
>>>>> chapter to chapter I will need to change the bash script, but this
>>>>> seems
>>>>> to
>>>>> be less typing than using the terminal.
>>>>>
>>>>>
>>>>> Thanks,  Jim
>>>>>
>>>>>
>>>>>  Ok cool, glad it works. It might be possible to get the path so you
>>>> don't
>>>> have to set it each time, try this:
>>>>
>>>> #!/bin/bash
>>>> IFS="/"
>>>> path=($1)
>>>> cd $(path[0:#path[*]])
>>>> python $1
>>>>
>>>>
>>>> # Warning, I'm not exactly a competent bash programmer so this may not
>>>> work
>>>> :-p
>>>>
>>>> Let me know if you need a hand to fix it,
>>>>
>>>> HTH,
>>>> Adam.
>>>>
>>>>
>>>>  I tried the new bash code but when I dropped a file on the launcher it
>>> just
>>> flashed an gave no output.  So I tried running the bash script
>>> (name=runpython) in a terminal and got this error:
>>>
>>> /home/jfb/runpython: line 4: path[0:#path[*]]: command not found
>>> Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
>>> [GCC 4.4.3] on linux2
>>> Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>>
>>>>>>
>>> I know even less about bash than you do, so I don't where to start to
>>> debug
>>> this.
>>>
>>>
>>> Thanks,  Jim
>>>
>>> Ok then, this time it's tested and not just improvised, here we go:
>>>
>>
>> #!/bin/bash
>>
>> script=$1 # Full path for calling the script later
>> orig_IFS=$IFS # This is to reset IFS so that "script" is correct
>> (otherwise
>> has spaces instead of /)
>> IFS="/"
>> path=( $1 )
>> IFS=$orig_IFS
>> last_ind=${#path[@]} # Works out the length of path
>> let "last_ind -= 1" # Sets last_ind to index of script name
>> len_path=${path[@]:0:last_ind} # Gets the path without the script name
>> let "len_path=${#len_path[0]} + 1" # This gives the length of the script
>> string upto just before the last /
>> cd ${script[@]:0:len_path} # cds to the path
>> python script
>>
>>
>> As pretty much my first non-trivial bash script it's probably horrible but
>> it seems to work.
>>
>> HTH,
>> Adam.
>>
>>
> There must be something different in our setups because it did not work for
> me.  If I run it from a terminal I get:
>
> jfb at jfb-ubuntu64:~$ /home/jfb/runpython_test bitmap_button.py
> /home/jfb/runpython_test: line 12: cd: b: No such file or directory
> python: can't open file 'script': [Errno 2] No such file or directory
> jfb at jfb-ubuntu64:~$
>
> Thanks  Jim
>
>
Oh cock, I missed a $ sign it should be "python $script". Seems to complain
about the path as well though, not sure about that one, I'll get back to you
later.

Adam.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100715/314ad3cd/attachment-0001.html>

From scarolan at gmail.com  Thu Jul 15 20:07:39 2010
From: scarolan at gmail.com (Sean Carolan)
Date: Thu, 15 Jul 2010 13:07:39 -0500
Subject: [Tutor] How to deal failed function and 0xDEADBEEF type errors...
Message-ID: <AANLkTim75M2MXu3PSlfLKZeHpsreUtsJlmvX96W5eQpA@mail.gmail.com>

Spoiler alert:  This was encountered while working on MIT OCW 6.000
problem set 4.

http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/ps4.py


My function returns a list as it should:

##############################
def nestEggFixed(salary, save, growthRate, years):
    yearlyreturn=[]
    nut = 0
    for i in range(0, years):
        # print "At the end of year",(i),"nut size is:",(nut)
        nut = nut * (1 + 0.01 * growthRate) + (salary * save * 0.01)
        yearlyreturn.append(nut)
    return yearlyreturn
##############################

print nestEggFixed(10000, 10, 15, 5)
[1000.0, 2150.0, 3472.5, 4993.375, 6742.381249999999]

So far so good right?  Not so fast, the test function provided by the
instructors is failing:

Here's the test function:

##############################
def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
##############################

Run it by itself and there's no output:

testNestEggFixed

Try to print it and it throws this error:

print testNestEggFixed
<function testNestEggFixed at 0x0214D5F0>

What am I missing here?  I even tried running all the code in the test
function in my script and it works fine.  It only fails when it's put
into a function.  I think I must be doing something wrong.

From emile at fenx.com  Thu Jul 15 20:27:03 2010
From: emile at fenx.com (Emile van Sebille)
Date: Thu, 15 Jul 2010 11:27:03 -0700
Subject: [Tutor] How to deal failed function and 0xDEADBEEF type
	errors...
In-Reply-To: <AANLkTim75M2MXu3PSlfLKZeHpsreUtsJlmvX96W5eQpA@mail.gmail.com>
References: <AANLkTim75M2MXu3PSlfLKZeHpsreUtsJlmvX96W5eQpA@mail.gmail.com>
Message-ID: <i1nk0e$jdb$1@dough.gmane.org>

On 7/15/2010 11:07 AM Sean Carolan said...
>
> Try to print it and it throws this error:
>
> print testNestEggFixed
> <function testNestEggFixed at 0x0214D5F0>


That's not an error -- that's what testNestEggFixed -- a function 
located at 0x0214D5F0.  If you intended to _execute_ the function, add 
parens and the appropriate parameters to your print statement.

HTH,

Emile


From marris1031 at gmail.com  Thu Jul 15 20:32:24 2010
From: marris1031 at gmail.com (Mary Morris)
Date: Thu, 15 Jul 2010 12:32:24 -0600
Subject: [Tutor] append, list and variables
Message-ID: <AANLkTimHIbqyTZgR7ykSdAhc7P-qwvbX3w4p4Eba4NF8@mail.gmail.com>

Hi,
I'm working on a program that parses through all of our source code at my
office and i need to get my code to print a list of the decorators.  I used
a find(@) to locate all the decorators, but I need to assign them to a
variable somehow to get it to print a list. How do I do this? How do I
assign a variable to all the indexed strings after the @ symbol?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100715/c1308112/attachment.html>

From emile at fenx.com  Thu Jul 15 20:58:13 2010
From: emile at fenx.com (Emile van Sebille)
Date: Thu, 15 Jul 2010 11:58:13 -0700
Subject: [Tutor] append, list and variables
In-Reply-To: <AANLkTimHIbqyTZgR7ykSdAhc7P-qwvbX3w4p4Eba4NF8@mail.gmail.com>
References: <AANLkTimHIbqyTZgR7ykSdAhc7P-qwvbX3w4p4Eba4NF8@mail.gmail.com>
Message-ID: <i1nlqs$qj7$1@dough.gmane.org>

On 7/15/2010 11:32 AM Mary Morris said...
> Hi,
> I'm working on a program that parses through all of our source code at my
> office and i need to get my code to print a list of the decorators.  I used
> a find(@) to locate all the decorators, but I need to assign them to a
> variable somehow to get it to print a list. How do I do this? How do I
> assign a variable to all the indexed strings after the @ symbol?
>

So, decorator lines start with an '@'.  Source files end in '.py'.

Pseudo code could be:
----
initialize result container

with each sourcefilename in globbed list:
   for eachline in opened(sourcefilename):
     if line.startswith('@'):
       append [sourcefilename, line] to result

# print it

for eachline in result:
   print eachline
----

Hope this gets you going,

Emile





From g.nius.ck at gmail.com  Thu Jul 15 21:47:41 2010
From: g.nius.ck at gmail.com (Christopher King)
Date: Thu, 15 Jul 2010 15:47:41 -0400
Subject: [Tutor] Request for help learning the right way to deal with
	listsin lists
In-Reply-To: <20100715120924.GA25972@scriptkitchen.com>
References: <mailman.2673.1278948588.1671.tutor@python.org>
	<359328.83032.qm@web44711.mail.sp1.yahoo.com>
	<i1h50d$4vu$1@dough.gmane.org>
	<20100715120924.GA25972@scriptkitchen.com>
Message-ID: <AANLkTinQUI2GRAemw9iMUz2WN-bs4EFOG5uFBgPlDiXF@mail.gmail.com>

I will spilt it up and add comments.

Books =\ #Assign to Books
[Book('War & Peace", [3, 56, 88]), #The first is a Book named 'War & Peace'
Book("Huck Finn", [2, 5, 19])] #You use the book class twice in a row, one
for each book


On Thu, Jul 15, 2010 at 8:09 AM, Payal <payal-python at scriptkitchen.com>wrote:

> On Tue, Jul 13, 2010 at 08:35:45AM +0100, Alan Gauld wrote:
> > If the data gets more complex you could put the data into a class:
> >
> > class Book:
> >      def __init__(self, title, pages=[]):
> >          self.title = title
> >          self.pages = pages
> >
> > Books = [ Book('War & Peace", [3,56,88]),
> >               Book("Huck Finn", [2,5,19]) ]
>
> Can someone please explain the above 2 lines?
>
> > for book in Books:
> >     print book.title, book.pages
>
> With warm regards,
> -Payal
> --
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100715/66a8b759/attachment.html>

From asmosis.asterix at gmail.com  Thu Jul 15 23:07:05 2010
From: asmosis.asterix at gmail.com (Daniel)
Date: Fri, 16 Jul 2010 00:07:05 +0300
Subject: [Tutor] Python Book recomandation!
Message-ID: <AANLkTinp00KIyiLBUcoHjkmOcyf50DGpgaKRJ0oNLMWe@mail.gmail.com>

Hello, I recently browsed the BeginnersGuide/NonProgrammers section of the
Python website, but I have a question regarding it. With what book I should
start learning Python? Or should I take them in the order they are presented
there on the website?I have no previous programming experience, thanks.



Have a great day!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100716/dff4c387/attachment.html>

From ehamiter at gmail.com  Thu Jul 15 23:22:49 2010
From: ehamiter at gmail.com (Eric Hamiter)
Date: Thu, 15 Jul 2010 16:22:49 -0500
Subject: [Tutor] Python Book recomandation!
In-Reply-To: <AANLkTinp00KIyiLBUcoHjkmOcyf50DGpgaKRJ0oNLMWe@mail.gmail.com>
References: <AANLkTinp00KIyiLBUcoHjkmOcyf50DGpgaKRJ0oNLMWe@mail.gmail.com>
Message-ID: <AANLkTikIwUy_mAsA-Qg-3D6Hi8OVpQ09gMftEldVEa31@mail.gmail.com>

Hi Daniel,

As a fellow complete beginner, I have actually started a web site that
details just this. I'm learning as I go and have tried to put together
a curriculum of sorts that will helpfully guide other newbies as well,
and reinforce what I'm learning for myself.

http://letslearnpython.com/

Pardon my own plug, but you are exactly the audience member I am
targeting. Everything I recommend with the exception of a paperback
book is free to access. I'm adding more "lessons" as I go, and
hopefully as I progress, I can make more specific recommendations.

You are off to a great start by asking this list; I've found the
people here are very friendly and extremely knowledgeable.

Thanks,

Eric


On Thu, Jul 15, 2010 at 4:07 PM, Daniel <asmosis.asterix at gmail.com> wrote:
> Hello, I recently browsed the BeginnersGuide/NonProgrammers section of the
> Python website, but I have a question regarding it. With what book I should
> start learning Python? Or should I take them in the order they are presented
> there on the website?I have no previous programming experience, thanks.
>
>
>
> Have a great day!
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

From webtourist at gmail.com  Fri Jul 16 00:00:46 2010
From: webtourist at gmail.com (Robert)
Date: Thu, 15 Jul 2010 18:00:46 -0400
Subject: [Tutor] Python Book recomandation!
In-Reply-To: <AANLkTinp00KIyiLBUcoHjkmOcyf50DGpgaKRJ0oNLMWe@mail.gmail.com>
References: <AANLkTinp00KIyiLBUcoHjkmOcyf50DGpgaKRJ0oNLMWe@mail.gmail.com>
Message-ID: <AANLkTinSND1FmQpNRE20DAHo2EuCKy-s8kvgHraDPNTw@mail.gmail.com>

'Building Skills in Python" by Steven Lott, This free book is simply awesome
http://homepage.mac.com/s_lott/books/python.html

I went thru the "short" books first : "Dive Into Python" and "Byte of
Python" - they are good for a bit of foundation then come to this one,
and this one rreinforces concepts and explain things in a much more
organized and clear-cut way.


On Thu, Jul 15, 2010 at 5:07 PM, Daniel <asmosis.asterix at gmail.com> wrote:
> Hello, I recently browsed the BeginnersGuide/NonProgrammers section of the
> Python website, but I have a question regarding it. With what book I should
> start learning Python? Or should I take them in the order they are presented
> there on the website?I have no previous programming experience, thanks.

From anand.shashwat at gmail.com  Fri Jul 16 00:01:37 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Fri, 16 Jul 2010 03:31:37 +0530
Subject: [Tutor] Python Book recomandation!
In-Reply-To: <AANLkTinp00KIyiLBUcoHjkmOcyf50DGpgaKRJ0oNLMWe@mail.gmail.com>
References: <AANLkTinp00KIyiLBUcoHjkmOcyf50DGpgaKRJ0oNLMWe@mail.gmail.com>
Message-ID: <AANLkTikji9SsStOY2eGoC6-CV1h48oMHqfDdbTRA-7mN@mail.gmail.com>

On Fri, Jul 16, 2010 at 2:37 AM, Daniel <asmosis.asterix at gmail.com> wrote:

> Hello, I recently browsed the BeginnersGuide/NonProgrammers section of the
> Python website, but I have a question regarding it. With what book I should
> start learning Python? Or should I take them in the order they are presented
> there on the website?I have no previous programming experience, thanks.
>

FWIW I feel going through official python tutorial and then making a project
helps better than anything else to learn python.

~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100716/f95e2e11/attachment.html>

From smokefloat at gmail.com  Fri Jul 16 00:04:24 2010
From: smokefloat at gmail.com (David Hutto)
Date: Thu, 15 Jul 2010 18:04:24 -0400
Subject: [Tutor] Python Book recomandation!
In-Reply-To: <AANLkTikIwUy_mAsA-Qg-3D6Hi8OVpQ09gMftEldVEa31@mail.gmail.com>
References: <AANLkTinp00KIyiLBUcoHjkmOcyf50DGpgaKRJ0oNLMWe@mail.gmail.com>
	<AANLkTikIwUy_mAsA-Qg-3D6Hi8OVpQ09gMftEldVEa31@mail.gmail.com>
Message-ID: <AANLkTinMjH6Vmgdl9zQr9Lrh5tT0wVh6lQDVH4we6Fk5@mail.gmail.com>

On Thu, Jul 15, 2010 at 5:22 PM, Eric Hamiter <ehamiter at gmail.com> wrote:
> Hi Daniel,
>
> As a fellow complete beginner, I have actually started a web site that
> details just this. I'm learning as I go and have tried to put together
> a curriculum of sorts that will helpfully guide other newbies as well,
> and reinforce what I'm learning for myself.
>
> http://letslearnpython.com/
>
> Pardon my own plug, but you are exactly the audience member I am
> targeting. Everything I recommend with the exception of a paperback
> book is free to access. I'm adding more "lessons" as I go, and
> hopefully as I progress, I can make more specific recommendations.
>
> You are off to a great start by asking this list; I've found the
> people here are very friendly and extremely knowledgeable.
>
> Thanks,
>
> Eric
>
>
> On Thu, Jul 15, 2010 at 4:07 PM, Daniel <asmosis.asterix at gmail.com> wrote:
>> Hello, I recently browsed the BeginnersGuide/NonProgrammers section of the
>> Python website, but I have a question regarding it. With what book I should
>> start learning Python? Or should I take them in the order they are presented
>> there on the website?I have no previous programming experience, thanks.
>>
>>
>>
>> Have a great day!
>>
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

I've done several, including Byte Of  Python, as well as Dive into
python, and this is the best so far:

inventwithpython.com/IYOCGwP_book1.pdf

Although each individually might not make you an immediate expert.
Each helps you gain knowledge by repeating some of what you know, and
then offering a different program in which these fundamentals operate.

 So the more you practice the fundamentals within the books,(and don't
forget the online tutorials available), the more user friendly Python
becomes.

.

From emylistsddg at gmail.com  Fri Jul 16 02:03:38 2010
From: emylistsddg at gmail.com (eMyListsDDg)
Date: Thu, 15 Jul 2010 17:03:38 -0700
Subject: [Tutor] str format conversion help
In-Reply-To: <850361.23381.qm@web86701.mail.ird.yahoo.com>
References: <AANLkTimu8Lr3nzdoGwcfML5v1IPVaDo6FbtgVwDyds-b@mail.gmail.com><AANLkTimk9DtHlyhU7z4WbNoJDaeW3FK3ErFuu1fHtjir@mail.gmail.com>
	<1237428025.20100714113502@gmail.com>
	<i1l322$l5r$1@dough.gmane.org> <150456423.20100714201555@gmail.com>
	<850361.23381.qm@web86701.mail.ird.yahoo.com>
Message-ID: <925863071.20100715170338@gmail.com>


yep, i noticed. ;^)

no prob, through your help, it is working the way i needed.

thanks



>> print "[%s]" % ('-'.join([hex(v) for v in  theValue]) )

> Oops, that leaves 0x at the front of each byte.

> You could strip that off with

> print "[%s]" % ('-'.join([hex(v)[2:] for v in  theValue]) )

> Sorry,

> Alan G.



-- 
Best regards,
 eMyListsDDg                            mailto:eMyListsDDg at gmail.com


From joseph.gulizia at gmail.com  Fri Jul 16 02:08:16 2010
From: joseph.gulizia at gmail.com (Joseph Gulizia)
Date: Thu, 15 Jul 2010 19:08:16 -0500
Subject: [Tutor] Python Book recomandation!
In-Reply-To: <AANLkTinMjH6Vmgdl9zQr9Lrh5tT0wVh6lQDVH4we6Fk5@mail.gmail.com>
References: <AANLkTinp00KIyiLBUcoHjkmOcyf50DGpgaKRJ0oNLMWe@mail.gmail.com>
	<AANLkTikIwUy_mAsA-Qg-3D6Hi8OVpQ09gMftEldVEa31@mail.gmail.com>
	<AANLkTinMjH6Vmgdl9zQr9Lrh5tT0wVh6lQDVH4we6Fk5@mail.gmail.com>
Message-ID: <AANLkTikYWrdY9LW4PN8hDcf1D5J6ZThsY4XoM7y8I6Mj@mail.gmail.com>

I've found "Snake Wrangling for Kids" http://code.google.com/p/swfk/  by
Jason Biggs an easy, fun and understandable free e-book.  I also have
started reading "Head First Programming" from O'Reilly which teaches
programming using Python.  I have others also but those two have been the
easiest to read.  YouTube also has many tutorials...some quite good.

Joe

On Thu, Jul 15, 2010 at 5:04 PM, David Hutto <smokefloat at gmail.com> wrote:

> On Thu, Jul 15, 2010 at 5:22 PM, Eric Hamiter <ehamiter at gmail.com> wrote:
> > Hi Daniel,
> >
> > As a fellow complete beginner, I have actually started a web site that
> > details just this. I'm learning as I go and have tried to put together
> > a curriculum of sorts that will helpfully guide other newbies as well,
> > and reinforce what I'm learning for myself.
> >
> > http://letslearnpython.com/
> >
> > Pardon my own plug, but you are exactly the audience member I am
> > targeting. Everything I recommend with the exception of a paperback
> > book is free to access. I'm adding more "lessons" as I go, and
> > hopefully as I progress, I can make more specific recommendations.
> >
> > You are off to a great start by asking this list; I've found the
> > people here are very friendly and extremely knowledgeable.
> >
> > Thanks,
> >
> > Eric
> >
> >
> > On Thu, Jul 15, 2010 at 4:07 PM, Daniel <asmosis.asterix at gmail.com>
> wrote:
> >> Hello, I recently browsed the BeginnersGuide/NonProgrammers section of
> the
> >> Python website, but I have a question regarding it. With what book I
> should
> >> start learning Python? Or should I take them in the order they are
> presented
> >> there on the website?I have no previous programming experience, thanks.
> >>
> >>
> >>
> >> Have a great day!
> >>
> >> _______________________________________________
> >> Tutor maillist  -  Tutor at python.org
> >> To unsubscribe or change subscription options:
> >> http://mail.python.org/mailman/listinfo/tutor
> >>
> >>
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
> I've done several, including Byte Of  Python, as well as Dive into
> python, and this is the best so far:
>
> inventwithpython.com/IYOCGwP_book1.pdf
>
> Although each individually might not make you an immediate expert.
> Each helps you gain knowledge by repeating some of what you know, and
> then offering a different program in which these fundamentals operate.
>
>  So the more you practice the fundamentals within the books,(and don't
> forget the online tutorials available), the more user friendly Python
> becomes.
>
> .
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100715/06e38f4d/attachment-0001.html>

From guilherme at gpfreitas.com  Fri Jul 16 02:08:30 2010
From: guilherme at gpfreitas.com (Guilherme P. de Freitas)
Date: Thu, 15 Jul 2010 20:08:30 -0400
Subject: [Tutor] Python Book recomandation!
In-Reply-To: <AANLkTikIwUy_mAsA-Qg-3D6Hi8OVpQ09gMftEldVEa31@mail.gmail.com>
References: <AANLkTinp00KIyiLBUcoHjkmOcyf50DGpgaKRJ0oNLMWe@mail.gmail.com>
	<AANLkTikIwUy_mAsA-Qg-3D6Hi8OVpQ09gMftEldVEa31@mail.gmail.com>
Message-ID: <AANLkTil4V1mGvGLPQNZxv2CA3i9F0dGFJDbaDoCWkGKL@mail.gmail.com>

On Thu, Jul 15, 2010 at 5:22 PM, Eric Hamiter <ehamiter at gmail.com> wrote:
> As a fellow complete beginner, I have actually started a web site that
> details just this. I'm learning as I go and have tried to put together
> a curriculum of sorts that will helpfully guide other newbies as well,
> and reinforce what I'm learning for myself.
>
> http://letslearnpython.com/

The first lesson on the link above suggests the tutorial "Learn Python the Hard
Way". One comment about it: it seems to teach Python 2.x series, as can be seen
from the print statements. I would advise most beginners to learn Python 3.

-- 
Guilherme P. de Freitas
http://www.gpfreitas.com

From cbc at unc.edu  Fri Jul 16 02:42:02 2010
From: cbc at unc.edu (Chris Calloway)
Date: Thu, 15 Jul 2010 20:42:02 -0400
Subject: [Tutor] Toronto PyCamp 2010
Message-ID: <4C3FAADA.2020207@unc.edu>

The University of Toronto Department of Physics brings PyCamp to Toronto 
on Monday, August 30 through Friday, September 3, 2010.

Register today at http://trizpug.org/boot-camp/torpy10/

For beginners, this ultra-low-cost Python Boot Camp makes you productive 
so you can get your work done quickly. PyCamp emphasizes the features 
which make Python a simpler and more efficient language. Following along 
with example Python PushUps? speeds your learning process in a modern 
high-tech classroom. Become a self-sufficient Python developer in just 
five days at PyCamp! Conducted on the campus of the University of 
Toronto, PyCamp comes with your own single OS/single developer copy of 
Wing Professional Python IDE.

-- 
Sincerely,

Chris Calloway
office: 332 Chapman Hall   phone: (919) 599-3530
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599

From alan.gauld at btinternet.com  Fri Jul 16 08:30:47 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 16 Jul 2010 07:30:47 +0100
Subject: [Tutor] Python Book recomandation!
References: <AANLkTinp00KIyiLBUcoHjkmOcyf50DGpgaKRJ0oNLMWe@mail.gmail.com>
Message-ID: <i1ouam$ae7$1@dough.gmane.org>


"Daniel" <asmosis.asterix at gmail.com> wrote

> Python website, but I have a question regarding it. With what book I 
> should
> start learning Python? Or should I take them in the order they are 
> presented
> there on the website?I have no previous programming experience, 
> thanks.

Don't try to read them all!

They all present much the same information just in different styles.
Some major on getting you writing code quickly, some present a more 
theoretical
basis first. Some use a common theme or project others use lots of 
different a
shorter projects. There is no right or best approach, pick the one 
that sems to
work best for you.

Much will depend on what you want to do with your new skills and what 
your
previous experience is. If you can already program in another language 
the
official tutor is probably the best starting place, but if you don't 
already
programme much of it will be meaningless.

The one that is best for you can only be decided by you!

HTH,

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



From alan.gauld at btinternet.com  Fri Jul 16 08:35:00 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 16 Jul 2010 07:35:00 +0100
Subject: [Tutor] How to deal failed function and 0xDEADBEEF type
	errors...
References: <AANLkTim75M2MXu3PSlfLKZeHpsreUtsJlmvX96W5eQpA@mail.gmail.com>
Message-ID: <i1ouij$b73$1@dough.gmane.org>


"Sean Carolan" <scarolan at gmail.com> wrote

> Run it by itself and there's no output:
>
> testNestEggFixed
>
> Try to print it and it throws this error:
>
> print testNestEggFixed
> <function testNestEggFixed at 0x0214D5F0>
>
> What am I missing here?

parentheses?

I assume you are from a Visual VBasic background?
Unlike VB Python requires you to have the parentheses
after the function name, even if there is nothing inside them.
Otherwise you are referring to a function *object* - which
is what the print statement told you...

HTH,


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


I even tried running all the code in the test
> function in my script and it works fine.  It only fails when it's 
> put
> into a function.  I think I must be doing something wrong.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 



From think123 at gmail.com  Fri Jul 16 09:19:39 2010
From: think123 at gmail.com (Ethan Wei)
Date: Fri, 16 Jul 2010 15:19:39 +0800
Subject: [Tutor] Python Book recomandation!
In-Reply-To: <i1ouam$ae7$1@dough.gmane.org>
References: <AANLkTinp00KIyiLBUcoHjkmOcyf50DGpgaKRJ0oNLMWe@mail.gmail.com>
	<i1ouam$ae7$1@dough.gmane.org>
Message-ID: <AANLkTin2ob8or8M5YwgsijxDc7B3IkvzuZO61feKAbsJ@mail.gmail.com>

For BOOK recommend:  <python cookbook>  my favor. :)

For promote you skill:  Find a short python source code(ex.from open source
project) and read it. you can learn more useful programing methods.


2010/7/16 Alan Gauld <alan.gauld at btinternet.com>

>
> "Daniel" <asmosis.asterix at gmail.com> wrote
>
>  Python website, but I have a question regarding it. With what book I
>> should
>> start learning Python? Or should I take them in the order they are
>> presented
>> there on the website?I have no previous programming experience, thanks.
>>
>
> Don't try to read them all!
>
> They all present much the same information just in different styles.
> Some major on getting you writing code quickly, some present a more
> theoretical
> basis first. Some use a common theme or project others use lots of
> different a
> shorter projects. There is no right or best approach, pick the one that
> sems to
> work best for you.
>
> Much will depend on what you want to do with your new skills and what your
> previous experience is. If you can already program in another language the
> official tutor is probably the best starting place, but if you don't
> already
> programme much of it will be meaningless.
>
> The one that is best for you can only be decided by you!
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100716/6c66803d/attachment.html>

From zuxoxus at gmail.com  Fri Jul 16 15:47:19 2010
From: zuxoxus at gmail.com (ZUXOXUS)
Date: Fri, 16 Jul 2010 15:47:19 +0200
Subject: [Tutor] I don't understand this code
In-Reply-To: <AANLkTim2IB_6Xls4QkaUizylUgFM1dcVhaMRgW2qIeSD@mail.gmail.com>
References: <AANLkTim2IB_6Xls4QkaUizylUgFM1dcVhaMRgW2qIeSD@mail.gmail.com>
Message-ID: <AANLkTilMcI6doTnsszvi1Kqo0eXeOwa4x6Ig-siCUIox@mail.gmail.com>

Hey,

thanks for your help!

I couldn't understand because I didn't see that further down in the code, as
Serdar Tumgoren said, the function was called:

secretWord = getRandomWord(words)

without that line I couldn't get it.

Thank you very much, everybody, great explanations.

Alan, I have been checking your tutorial too, great job.



2010/7/13 ZUXOXUS <zuxoxus at gmail.com>

> Hi,
>
> I am a true beginner in programming, and im learning with
> inventwithpython.com.
>
> There's something I dont understand, and i would really appreciate any
> help.
>
> In chapter 9, the one about the Hangman game, I don't get the block of code
> in line 61
>
> 59.  words = 'ant baboon badger bat bear'
> 60.
>
>    1. def getRandomWord(wordList):
>    2.     # This function returns a random string from the passed list of
>    strings.
>    3.     wordIndex = random.randint(0, len(wordList) - 1)
>    4.     return wordList[wordIndex]
>
>
> The thing is, the "passed list of strings" is called "words", not
> "wordList", so I see it shouldn't work.
>
> On the other hand, the variable "wordList" is defined nowhere!
>
> The code is ok, because the program runs ok. So there is somethings that i
> dont get.
>
> Thank you very much in advance.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100716/ef5a76fb/attachment.html>

From cheesman at titan.physx.u-szeged.hu  Fri Jul 16 16:16:58 2010
From: cheesman at titan.physx.u-szeged.hu (Andy)
Date: Fri, 16 Jul 2010 16:16:58 +0200
Subject: [Tutor] Removing GB pound symbols from Beautiful soup output
Message-ID: <4C4069DA.6020608@titan.physx.u-szeged.hu>

Dear Nice people

I've been using beautiful soup to filter the BBC's rss feed. However, 
recently the bbc have changed the feed and it is causing me problems 
with the pound(money) symbol. The initial error was "UnicodeEncodeError: 
'ascii' codec can't encode character u'\xa3'" which means that the 
default encoding can't process this (unicode) character. I was having 
simular problems with HTML characters appearing but I used a simple 
regex system to remove/substitute them to something suitable.
I tried applying the same approach and make a generic regex patten 
(re.compile(u"""\u\[A-Fa-f0-9\]\{4\}""") but this fails because it 
doesn't follow the standard patten for ascii. I'm not sure that I 100% 
understand the unicode system but is there a simple way to 
remove/subsitute these non ascii strings?

Thanks for any help!

Andy

From think123 at gmail.com  Fri Jul 16 17:29:06 2010
From: think123 at gmail.com (Ethan Wei)
Date: Fri, 16 Jul 2010 23:29:06 +0800
Subject: [Tutor] Removing GB pound symbols from Beautiful soup output
In-Reply-To: <4C4069DA.6020608@titan.physx.u-szeged.hu>
References: <4C4069DA.6020608@titan.physx.u-szeged.hu>
Message-ID: <AANLkTikhNNArG8svB_AVAzTDE2Uq0iZs_67oO_X7tEJv@mail.gmail.com>

1st. what's the BBC's rss page coding? UTF-8 or something.
2nd. confirm you file coding and document coding equate rss page coding.
3rd. add fromEncoding to you BeautifulSoup instance?

>  ex. soup = BeautifulSoup(html,fromEncoding="utf-8")
>


2010/7/16 Andy <cheesman at titan.physx.u-szeged.hu>

> Dear Nice people
>
> I've been using beautiful soup to filter the BBC's rss feed. However,
> recently the bbc have changed the feed and it is causing me problems with
> the pound(money) symbol. The initial error was "UnicodeEncodeError: 'ascii'
> codec can't encode character u'\xa3'" which means that the default encoding
> can't process this (unicode) character. I was having simular problems with
> HTML characters appearing but I used a simple regex system to
> remove/substitute them to something suitable.
> I tried applying the same approach and make a generic regex patten
> (re.compile(u"""\u\[A-Fa-f0-9\]\{4\}""") but this fails because it doesn't
> follow the standard patten for ascii. I'm not sure that I 100% understand
> the unicode system but is there a simple way to remove/subsitute these non
> ascii strings?
>
> Thanks for any help!
>
> Andy
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100716/a49b2543/attachment.html>

From marris1031 at gmail.com  Fri Jul 16 17:37:53 2010
From: marris1031 at gmail.com (Mary Morris)
Date: Fri, 16 Jul 2010 09:37:53 -0600
Subject: [Tutor] append, list and variables
In-Reply-To: <i1nlqs$qj7$1@dough.gmane.org>
References: <AANLkTimHIbqyTZgR7ykSdAhc7P-qwvbX3w4p4Eba4NF8@mail.gmail.com>
	<i1nlqs$qj7$1@dough.gmane.org>
Message-ID: <AANLkTikwVFdOx5I_ckSGRDBbOKMKd2z_7VLqR67gElnF@mail.gmail.com>

Thanks-that helps a lot.
The only question I have about your pseudocode is what the 'initialize
result container' does.  I'm pretty new to python and scripting in general
so I'm still trying to figure everything out.

On Thu, Jul 15, 2010 at 12:58 PM, Emile van Sebille <emile at fenx.com> wrote:

> On 7/15/2010 11:32 AM Mary Morris said...
>
>  Hi,
>> I'm working on a program that parses through all of our source code at my
>> office and i need to get my code to print a list of the decorators.  I
>> used
>> a find(@) to locate all the decorators, but I need to assign them to a
>> variable somehow to get it to print a list. How do I do this? How do I
>> assign a variable to all the indexed strings after the @ symbol?
>>
>>
> So, decorator lines start with an '@'.  Source files end in '.py'.
>
> Pseudo code could be:
> ----
> initialize result container
>
> with each sourcefilename in globbed list:
>  for eachline in opened(sourcefilename):
>    if line.startswith('@'):
>      append [sourcefilename, line] to result
>
> # print it
>
> for eachline in result:
>  print eachline
> ----
>
> Hope this gets you going,
>
> Emile
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100716/354645d3/attachment.html>

From emile at fenx.com  Fri Jul 16 19:54:01 2010
From: emile at fenx.com (Emile van Sebille)
Date: Fri, 16 Jul 2010 10:54:01 -0700
Subject: [Tutor] append, list and variables
In-Reply-To: <AANLkTikwVFdOx5I_ckSGRDBbOKMKd2z_7VLqR67gElnF@mail.gmail.com>
References: <AANLkTimHIbqyTZgR7ykSdAhc7P-qwvbX3w4p4Eba4NF8@mail.gmail.com>	<i1nlqs$qj7$1@dough.gmane.org>
	<AANLkTikwVFdOx5I_ckSGRDBbOKMKd2z_7VLqR67gElnF@mail.gmail.com>
Message-ID: <i1q683$p8p$1@dough.gmane.org>

On 7/16/2010 8:37 AM Mary Morris said...
> Thanks-that helps a lot.
> The only question I have about your pseudocode is what the 'initialize
> result container' does.  I'm pretty new to python and scripting in general
> so I'm still trying to figure everything out.

It creates an empty data storage container for use within the processing 
loop -- if it wasn't defined before use, you'd get an error the first 
time you tried to append to it.  There's some good info in the tutorial 
-- see http://docs.python.org/tutorial/datastructures.html for details.

Emile



>
> On Thu, Jul 15, 2010 at 12:58 PM, Emile van Sebille<emile at fenx.com>  wrote:
>
>> On 7/15/2010 11:32 AM Mary Morris said...
>>
>>   Hi,
>>> I'm working on a program that parses through all of our source code at my
>>> office and i need to get my code to print a list of the decorators.  I
>>> used
>>> a find(@) to locate all the decorators, but I need to assign them to a
>>> variable somehow to get it to print a list. How do I do this? How do I
>>> assign a variable to all the indexed strings after the @ symbol?
>>>
>>>
>> So, decorator lines start with an '@'.  Source files end in '.py'.
>>
>> Pseudo code could be:
>> ----
>> initialize result container
>>
>> with each sourcefilename in globbed list:
>>   for eachline in opened(sourcefilename):
>>     if line.startswith('@'):
>>       append [sourcefilename, line] to result
>>
>> # print it
>>
>> for eachline in result:
>>   print eachline
>> ----
>>
>> Hope this gets you going,
>>
>> Emile
>>
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



From piotr-kam at o2.pl  Fri Jul 16 21:44:07 2010
From: piotr-kam at o2.pl (pk)
Date: Fri, 16 Jul 2010 21:44:07 +0200
Subject: [Tutor] append, list and variables
In-Reply-To: <i1q683$p8p$1@dough.gmane.org>
References: <AANLkTimHIbqyTZgR7ykSdAhc7P-qwvbX3w4p4Eba4NF8@mail.gmail.com>
	<i1nlqs$qj7$1@dough.gmane.org>
	<AANLkTikwVFdOx5I_ckSGRDBbOKMKd2z_7VLqR67gElnF@mail.gmail.com>
	<i1q683$p8p$1@dough.gmane.org>
Message-ID: <op.vfybrtih10k764@user-391870>

Dnia 16-07-2010 o 19:54:01 Emile van Sebille <emile at fenx.com> napisa?(a):

> On 7/16/2010 8:37 AM Mary Morris said...
>> Thanks-that helps a lot.
>> The only question I have about your pseudocode is what the 'initialize
>> result container' does. I'm pretty new to python and scripting ingeneral
>> so I'm still trying to figure everything out.
>
> It creates an empty data storage container for use within the processing 
> loop -- if it wasn't defined before use, you'd get an error the first 
> time you tried to append to it. There's some good info in the tutorial--  
> see http://docs.python.org/tutorial/datastructures.html for details.
>
> Emile
>

The data structure talked about is a *list* and *  
['one','two'].append('e.g. a string') * is one of the list methods.
So it can be written like this:
a_result_container_aka_simply_a_list =  [ ]
a_result_container_aka_simply_a_list.append('something')
print a_result_container_aka_simply_a_list

In general, the shorter and more descriptive a variable name is, the  
better.

You can learn more about Python's data structures and the basic concepts  
of programming using the two books that I've found most useful - of course  
there are many more other good books that can be used.

These books are:
1. "Learn to Program" by Alan Gauld. It's more tutorial-like in style than  
the next one:
2. "How to Think Like a Computer Scientist" by Jeffrey Elkner, Allen B.  
Downey and Chris Meyers.
It's more like a school textbook with exercises at the end of each chapter  
and chapter 9 is called "Lists".
I've used them both to look at the same concepts from different  
perspectives because Alan's book gives more information about programming  
in general while the "How to Think..." is more dry, monotonous and  
impersonal which can be tiring at times.

"The Python Tutorial" by Guido van Rossum is okay too (it's short and  
comprehensive) but it's mainly directed to experienced programmers who can  
already program in at least one language - at least that's my impression.

Regards,
Piotr

>> On Thu, Jul 15, 2010 at 12:58 PM, Emile van Sebille<emile at fenx.com> 
>> wrote:
>>
>>> On 7/15/2010 11:32 AM Mary Morris said...
>>>
>>> Hi,
>>>> I'm working on a program that parses through all of our source codeat  
>>>> my
>>>> office and i need to get my code to print a list of the decorators. I
>>>> used
>>>> a find(@) to locate all the decorators, but I need to assign them to a
>>>> variable somehow to get it to print a list. How do I do this? How do I
>>>> assign a variable to all the indexed strings after the @ symbol?
>>>>
>>>>
>>> So, decorator lines start with an '@'. Source files end in '.py'.
>>>
>>> Pseudo code could be:
>>> ----
>>> initialize result container
>>>
>>> with each sourcefilename in globbed list:
>>> for eachline in opened(sourcefilename):
>>> if line.startswith('@'):
>>> append [sourcefilename, line] to result
>>>
>>> # print it
>>>
>>> for eachline in result:
>>> print eachline
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100716/c07f2ca1/attachment.html>

From steve at pearwood.info  Sat Jul 17 02:57:46 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 17 Jul 2010 10:57:46 +1000
Subject: [Tutor] append, list and variables
In-Reply-To: <op.vfybrtih10k764@user-391870>
References: <AANLkTimHIbqyTZgR7ykSdAhc7P-qwvbX3w4p4Eba4NF8@mail.gmail.com>
	<i1q683$p8p$1@dough.gmane.org> <op.vfybrtih10k764@user-391870>
Message-ID: <201007171057.47479.steve@pearwood.info>

On Sat, 17 Jul 2010 05:44:07 am pk wrote:

> In general, the shorter and more descriptive a variable name is, 
> the better.

That's a generalisation that is contradictory. Short works against 
descriptive. Compare:

n  # nice and short
number_of_widgets_ordered  # nice and descriptive, if a bit wordy
widgets_ordered  # a happy medium

Which is appropriate depends on the context. Generally, descriptive 
names are self-documenting and are to be preferred, but it is possible 
to overdo it:

def multiply_two_numbers_and_add_one(
    first_number_to_multiply_by, second_number_to_multiply_by
    ):
    return first_number_to_multiply_by*second_number_to_multiply_by + 1


The more terse version is simple enough to understand:

def mult_plus_one(x, y):
    return x*y + 1



-- 
Steven D'Aprano

From rdmoores at gmail.com  Sat Jul 17 08:32:52 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Fri, 16 Jul 2010 23:32:52 -0700
Subject: [Tutor] now = ctime()[11:20]
Message-ID: <AANLkTindQFSX8N2100z5tY_Wq4SCQPh1Ou3J6KyKjRjD@mail.gmail.com>

Please see <http://tutoree7.pastebin.com/azLrNL0n>

Foolishly, without thinking it through, I expected the 2 prints to
show different times. I understood right away why they were identical,
but then I began to wonder how to create an "alias" for
"ctime()[11:20]" so I wouldn't have to keep typing or pasting it.
"now" would be fine. But how to get it to execute ctime()?

Thanks,

Dick Moores

From alan.gauld at btinternet.com  Sat Jul 17 09:03:10 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 17 Jul 2010 08:03:10 +0100
Subject: [Tutor] now = ctime()[11:20]
References: <AANLkTindQFSX8N2100z5tY_Wq4SCQPh1Ou3J6KyKjRjD@mail.gmail.com>
Message-ID: <i1rkje$hs0$1@dough.gmane.org>


"Richard D. Moores" <rdmoores at gmail.com> wrote 

> but then I began to wonder how to create an "alias" for
> "ctime()[11:20]" so I wouldn't have to keep typing or pasting it.
> "now" would be fine. But how to get it to execute ctime()?

Create a function?

def myNow():
     return ctime()[11:20]

Or am I missing something?


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



From rabidpoobear at gmail.com  Sat Jul 17 09:08:11 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sat, 17 Jul 2010 02:08:11 -0500
Subject: [Tutor] now = ctime()[11:20]
In-Reply-To: <AANLkTindQFSX8N2100z5tY_Wq4SCQPh1Ou3J6KyKjRjD@mail.gmail.com>
References: <AANLkTindQFSX8N2100z5tY_Wq4SCQPh1Ou3J6KyKjRjD@mail.gmail.com>
Message-ID: <EFE74545-A00C-4F5A-8DEA-A0C1FA585388@gmail.com>

If you are asking how to get a variable to call a function each time it's accessed... Well that's kind of a weird request. I know you can create properties in a class that act like variables but you can do whatever you want behind the scenes, like calling the now() function on each access. A much more clear way to do this would be to create a function that calls the now function and just call your function whenever you want the value. Is there a specific reason why you would prefer to solve this without having to type 2 extra characters () and in turn make your code more readable and logical? The problem with the approach you hint at is that then the function call is implicit. What if someone else wanted to use your variable in a tight loop? They don't probably expect or want your variable to automatically update itself.

Also are you aware of the timeit module for dete

Perhaps I misunderstood your intent.

Sent from my iPhone

On Jul 17, 2010 at 1:32 AM, "Richard D. Moores" <rdmoores at gmail.com> wrote:

> Please see <http://tutoree7.pastebin.com/azLrNL0n>
> 
> Foolishly, without thinking it through, I expected the 2 prints to
> show different times. I understood right away why they were identical,
> but then I began to wonder how to create an "alias" for
> "ctime()[11:20]" so I wouldn't have to keep typing or pasting it.
> "now" would be fine. But how to get it to execute ctime()?
> 
> Thanks,
> 
> Dick Moores
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From rabidpoobear at gmail.com  Sat Jul 17 09:10:08 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sat, 17 Jul 2010 02:10:08 -0500
Subject: [Tutor] now = ctime()[11:20]
In-Reply-To: <AANLkTindQFSX8N2100z5tY_Wq4SCQPh1Ou3J6KyKjRjD@mail.gmail.com>
References: <AANLkTindQFSX8N2100z5tY_Wq4SCQPh1Ou3J6KyKjRjD@mail.gmail.com>
Message-ID: <8C3885AE-088D-47FD-BC52-7D0B66A14533@gmail.com>

Sorry the iPhone email client is terrible. It sent the previous email before I was done writing it. Anyway, the timeit module is available whenever you want to profile something and determine how long it takes to run.

Sent from my iPhone

On Jul 17, 2010, at 1:32 AM, "Richard D. Moores" <rdmoores at gmail.com> wrote:

> Please see <http://tutoree7.pastebin.com/azLrNL0n>
> 
> Foolishly, without thinking it through, I expected the 2 prints to
> show different times. I understood right away why they were identical,
> but then I began to wonder how to create an "alias" for
> "ctime()[11:20]" so I wouldn't have to keep typing or pasting it.
> "now" would be fine. But how to get it to execute ctime()?
> 
> Thanks,
> 
> Dick Moores
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From lang at tharin.com  Sat Jul 17 09:10:06 2010
From: lang at tharin.com (Lang Hurst)
Date: Sat, 17 Jul 2010 00:10:06 -0700
Subject: [Tutor] Strange sqlite3 behavior
Message-ID: <4C41574E.2070601@tharin.com>

I just had the weirdest issue with sqlite3.  I was trying to update a 
field to "Active".  I have a little database of students and sometimes 
they get sent to juvi, or just check out for a couple of months and show 
back up.  Anyway, I wanted to just have a field that had either "Active" 
or "Inactive".  I know, could go all boolean, but wanted to leave my 
options open.

Anyway, my code was along the lines of

    UPDATE students SET active="Inactive" where id="123456"


That would work, but

    UPDATE students SET active="Active" where id="123456"


wouldn't.  It wouldn't do anything, the field still held "Inactive".  I 
tried it manually through sqlite3browser and had the same result.  Strange.

    UPDATE students SET active="Bob Sagat" where id="123456"


worked.  Anything but "Active" works.  I was unable to update to 
"Active".  You can imagine how frustrating this was.  When I finally 
realized that it was only Active that didn't work, I changed my program 
to either "Active Student" or "Inactive Student" and it works fine.

Just had to post this somewhere, after loosing even more hair.

-Lang


-- 
There are no stupid questions, just stupid people.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100717/b8248656/attachment.html>

From mail at timgolden.me.uk  Sat Jul 17 11:04:49 2010
From: mail at timgolden.me.uk (Tim Golden)
Date: Sat, 17 Jul 2010 10:04:49 +0100
Subject: [Tutor] Strange sqlite3 behavior
In-Reply-To: <4C41574E.2070601@tharin.com>
References: <4C41574E.2070601@tharin.com>
Message-ID: <4C417231.5050001@timgolden.me.uk>

On 17/07/2010 8:10 AM, Lang Hurst wrote:
> I just had the weirdest issue with sqlite3.  I was trying to update a
> field to "Active".  I have a little database of students and sometimes
> they get sent to juvi, or just check out for a couple of months and show
> back up.  Anyway, I wanted to just have a field that had either "Active"
> or "Inactive".  I know, could go all boolean, but wanted to leave my
> options open.
>
> Anyway, my code was along the lines of
>
>      UPDATE students SET active="Inactive" where id="123456"
>
>
> That would work, but
>
>      UPDATE students SET active="Active" where id="123456"
>
>
> wouldn't.  It wouldn't do anything, the field still held "Inactive".

My guess -- without bothering to check the sqlite docs -- is that
sqlite uses single quotes to delimit strings and double quotes to
delimit column. Or at least that it can be set up to do that. If
that is the case then "Active" is taken to refer to the column
active and not to the string active. So you're just setting it
to itself.

Try it with 'Active' instead.

TJG

From piotr-kam at o2.pl  Sat Jul 17 11:31:40 2010
From: piotr-kam at o2.pl (pk)
Date: Sat, 17 Jul 2010 11:31:40 +0200
Subject: [Tutor] append, list and variables
In-Reply-To: <201007171057.47479.steve@pearwood.info>
References: <AANLkTimHIbqyTZgR7ykSdAhc7P-qwvbX3w4p4Eba4NF8@mail.gmail.com>
	<i1q683$p8p$1@dough.gmane.org> <op.vfybrtih10k764@user-391870>
	<201007171057.47479.steve@pearwood.info>
Message-ID: <op.vfzd22pr10k764@user-391870>

Dnia 17-07-2010 o 02:57:46 Steven D'Aprano <steve at pearwood.info>  
napisa?(a):

> On Sat, 17 Jul 2010 05:44:07 am pk wrote:
>
>> In general, the shorter and more descriptive a variable name is,
>> the better.
>
> That's a generalisation that is contradictory. Short works against
> descriptive. Compare:

Well, yes I agree. I've chosen a wrong word in this context. By writing
"descriptive" I meant that it should be as *informative, full of meaning
and precision* as possible; and at the same time as concise as possible.  
The word "meaningful" would probably be appropriate here.
Achieving the two goals can sometimes be hard and if there're no or few
comments, a program - especially a longer one - can be difficult to read
and understand. Fortunately, Python is not Perl (with its unnecessarily
rich syntax, terseness, names containing punctuation and special
characters), so in most cases it is easy to see what is going on - at
least I think so.

Wow, that's very general what I've just written and very much a repetition
(rephrasing) of your words, but I wanted to be clear.

Regards,
Piotr


> n  # nice and short
> number_of_widgets_ordered  # nice and descriptive, if a bit wordy
> widgets_ordered  # a happy medium
>
> Which is appropriate depends on the context. Generally, descriptive
> names are self-documenting and are to be preferred, but it is possible
> to overdo it:
>
> def multiply_two_numbers_and_add_one(
>     first_number_to_multiply_by, second_number_to_multiply_by
>     ):
>     return first_number_to_multiply_by*second_number_to_multiply_by + 1
>
>
> The more terse version is simple enough to understand:
>
> def mult_plus_one(x, y):
>     return x*y + 1
>
>

From rdmoores at gmail.com  Sat Jul 17 12:59:34 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 17 Jul 2010 03:59:34 -0700
Subject: [Tutor] now = ctime()[11:20]
In-Reply-To: <i1rkje$hs0$1@dough.gmane.org>
References: <AANLkTindQFSX8N2100z5tY_Wq4SCQPh1Ou3J6KyKjRjD@mail.gmail.com> 
	<i1rkje$hs0$1@dough.gmane.org>
Message-ID: <AANLkTinBbZvULdhFnFYq9EygL5e2DrXFLHJ8LdKswPpi@mail.gmail.com>

On Sat, Jul 17, 2010 at 00:03, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Richard D. Moores" <rdmoores at gmail.com> wrote
>>
>> but then I began to wonder how to create an "alias" for
>> "ctime()[11:20]" so I wouldn't have to keep typing or pasting it.
>> "now" would be fine. But how to get it to execute ctime()?
>
> Create a function?
>
> def myNow():
> ? ?return ctime()[11:20]

Yeah! Why didn't I think of that?

> Or am I missing something?

Only that I'm slower than you thought I was. :)

Thanks, Alan.

Dick

From rdmoores at gmail.com  Sat Jul 17 13:25:50 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 17 Jul 2010 04:25:50 -0700
Subject: [Tutor] now = ctime()[11:20]
In-Reply-To: <EFE74545-A00C-4F5A-8DEA-A0C1FA585388@gmail.com>
References: <AANLkTindQFSX8N2100z5tY_Wq4SCQPh1Ou3J6KyKjRjD@mail.gmail.com> 
	<EFE74545-A00C-4F5A-8DEA-A0C1FA585388@gmail.com>
Message-ID: <AANLkTikLEBeBiETg8S_KfHW0uqzveV-ewQ_MmDXnK6V9@mail.gmail.com>

On Sat, Jul 17, 2010 at 00:08, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> If you are asking how to get a variable to call a function each time it's accessed... Well that's kind of a weird request. I know you can create properties in a class that act like variables but you can do whatever you want behind the scenes, like calling the now() function on each access. A much more clear way to do this would be to create a function that calls the now function and just call your function whenever you want the value.

That's essentially Alan's suggestion, right? I've adopted it. See the
current state of the script I'm working on at
<http://tutoree7.pastebin.com/5XYaaNfp>. (I'll be posting a separate
question about it.)

 >Is there a specific reason why you would prefer to solve this
without having to type 2 extra characters ()

Actually, at age 73 I have trouble remembering the [11:20] part.

>and in turn make your code more readable and logical? The problem with the approach you hint at is that then the function call is implicit. What if someone else wanted to use your variable in a tight loop? They don't probably expect or want your variable to automatically update itself.

Point taken, and instead I'm going with Alan's function. But also,
this script is only for my own use, and the calling of ctime()[11:20]
is just so I can see where the script is bogging down. Turns out the
problem is that the writing of the long string of digits gets close to
exhausting my laptop's memory. But that's for another thread.

> Also are you aware of the timeit module for dete

I used to use it to time snippets at the command line. I've never used
it in a script. I'll check it out again. Usually if I time something
within a script I do it by using t0 = time() and t1 = time() and
printing the difference.

> Perhaps I misunderstood your intent.

I don't think so.

Thanks, Luke.

Dick

From rdmoores at gmail.com  Sat Jul 17 14:01:56 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 17 Jul 2010 05:01:56 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
Message-ID: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>

That's the goal of the latest version of my script at
<http://tutoree7.pastebin.com/5XYaaNfp>. The best I've been able to do
so far is a file with 800 million digits.

But it seems the writing of 800 million digits is the limit for the
amount of memory my laptop has (4 GB). So my question is, how can I do
this differently? I'm pretty brand new to opening and writing files.
Here, I can't write many shorter lines, because the end result I seek
is one long string. But am I correct?

I'd appreciate any advice.

BTW line 29 was added after getting the outputs noted at the bottom of
the script. Using close() does seem to shorten the time it takes for
my laptop to become usable again, but it's not decisive. Sometimes I
have to reboot in order to get healthy again. (64-bit Vista).

BTW2 It's probably not obvious why the list comprehension (line 19)
has random.choice(d) where d is '0123456789'. Without that, the random
ints of 1000 digits would never begin with a '0'. So I give them a
chance to by prefixing one random digit using choice(d), and cutting
the length of the rest from 1000 to 999.

Dick

From hugo.yoshi at gmail.com  Sat Jul 17 14:41:17 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sat, 17 Jul 2010 14:41:17 +0200
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
Message-ID: <AANLkTinEwOsSeAl8Znjf2tnQlRGHf1b1oKRmIb6rGJYV@mail.gmail.com>

On Sat, Jul 17, 2010 at 2:01 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
> That's the goal of the latest version of my script at
> <http://tutoree7.pastebin.com/5XYaaNfp>. The best I've been able to do
> so far is a file with 800 million digits.
>
> But it seems the writing of 800 million digits is the limit for the
> amount of memory my laptop has (4 GB). So my question is, how can I do
> this differently? I'm pretty brand new to opening and writing files.
> Here, I can't write many shorter lines, because the end result I seek
> is one long string. But am I correct?
>

You are not, and it would have been quite trivial to verify that:

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("test.txt", 'w')
>>> f.write('hello')
>>> f.write('world\n')
>>> f.close()
>>>
$ cat test.txt
helloworld
$

As you can see, two subsequent writes will end up on a single line. If
you want a newline character, you have to specify it yourself, like I
did after the second write. So you can generate your large number in
small pieces, no problem at all.

Hugo

From bgailer at gmail.com  Sat Jul 17 14:43:38 2010
From: bgailer at gmail.com (bob gailer)
Date: Sat, 17 Jul 2010 08:43:38 -0400
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
Message-ID: <4C41A57A.80306@gmail.com>

On 7/17/2010 8:01 AM, Richard D. Moores wrote:
> That's the goal of the latest version of my script at
> <http://tutoree7.pastebin.com/5XYaaNfp>. The best I've been able to do
> so far is a file with 800 million digits.
>
> But it seems the writing of 800 million digits is the limit for the
> amount of memory my laptop has (4 GB). So my question is, how can I do
> this differently? I'm pretty brand new to opening and writing files.
> Here, I can't write many shorter lines, because the end result I seek
> is one long string. But am I correct?
>    

Not correct. Check this out:

f = open("c:\test.txt", "w")
f.write("1234")
f.write("5678")
print open("c:\test.txt").read()

When you say "line" I assume you mean text followed by whatever the OS defines as end-of-line or end-of-record.

To write such a line in Python you must include "\n" at the end.

[snip]


-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From breamoreboy at yahoo.co.uk  Sat Jul 17 15:01:21 2010
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 17 Jul 2010 14:01:21 +0100
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
Message-ID: <i1s9j3$k3t$1@dough.gmane.org>

On 17/07/2010 13:01, Richard D. Moores wrote:
> That's the goal of the latest version of my script at
> <http://tutoree7.pastebin.com/5XYaaNfp>. The best I've been able to do
> so far is a file with 800 million digits.
>
> But it seems the writing of 800 million digits is the limit for the
> amount of memory my laptop has (4 GB). So my question is, how can I do
> this differently? I'm pretty brand new to opening and writing files.
> Here, I can't write many shorter lines, because the end result I seek
> is one long string. But am I correct?
>
> I'd appreciate any advice.
>
> BTW line 29 was added after getting the outputs noted at the bottom of
> the script. Using close() does seem to shorten the time it takes for
> my laptop to become usable again, but it's not decisive. Sometimes I
> have to reboot in order to get healthy again. (64-bit Vista).
>
> BTW2 It's probably not obvious why the list comprehension (line 19)
> has random.choice(d) where d is '0123456789'. Without that, the random
> ints of 1000 digits would never begin with a '0'. So I give them a
> chance to by prefixing one random digit using choice(d), and cutting
> the length of the rest from 1000 to 999.
>
> Dick
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

As an alternative to the suggestions given so far, why not open the file 
for write in binary mode, i.e. use 'wb' instead of 'w', and don't bother 
converting to strings?  Then when reading the file use 'rb' instead of 'r'.

HTH.

Mark Lawrence.


From bgailer at gmail.com  Sat Jul 17 15:34:06 2010
From: bgailer at gmail.com (bob gailer)
Date: Sat, 17 Jul 2010 09:34:06 -0400
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <i1s9j3$k3t$1@dough.gmane.org>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<i1s9j3$k3t$1@dough.gmane.org>
Message-ID: <4C41B14E.2080300@gmail.com>

On 7/17/2010 9:01 AM, Mark Lawrence wrote:

[snip]
>
> As an alternative to the suggestions given so far, why not open the 
> file for write in binary mode, i.e. use 'wb' instead of 'w', and don't 
> bother converting to strings?  Then when reading the file use 'rb' 
> instead of 'r'.

You can only write strings to files. See 6.9 in the documentation:

file.write(/str/)
    Write a string to the file

b mode only affects how line ends are handled. See 2. Built-in Functions:

The default is to use text mode, which may convert '\n' characters to a 
platform-specific representation on writing and back on reading. Thus, 
when opening a binary file, you should append 'b' to the /mode/ value to 
open the file in binary mode, which will improve portability. (Appending 
'b' is useful even on systems that don't treat binary and text files 
differently, where it serves as documentation.)


-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100717/7c8e870b/attachment.html>

From hugo.yoshi at gmail.com  Sat Jul 17 15:47:53 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sat, 17 Jul 2010 15:47:53 +0200
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <4C41B14E.2080300@gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<i1s9j3$k3t$1@dough.gmane.org> <4C41B14E.2080300@gmail.com>
Message-ID: <AANLkTinPzOHf1NkRPHpexGQY6mtVc7u1Cg_6Om-U6aVN@mail.gmail.com>

On Sat, Jul 17, 2010 at 3:34 PM, bob gailer <bgailer at gmail.com> wrote:
>
> You can only write strings to files. See 6.9 in the documentation:
> file.write(str) Write a string to the file b mode only affects how line ends
> are handled. See 2. Built-in Functions:
>
> The default is to use text mode, which may convert '\n' characters to a
> platform-specific representation on writing and back on reading. Thus, when
> opening a binary file, you should append 'b' to the mode value to open the
> file in binary mode, which will improve portability. (Appending 'b' is
> useful even on systems that don?t treat binary and text files differently,
> where it serves as documentation.)
>

me and Bob are in tune, it seems, I was composing the same message.

Would like to add that in python 3.x the 'b' does make a difference,
since read and write will use the 'bytes' type. Also, if you don't
mind a binary file, I would also like to suggest the following
non-python solution:

$ dd if=/dev/urandom of=rand_numbers.txt count=100MB

and adjust the count argument to your liking.

Hugo

From rdmoores at gmail.com  Sat Jul 17 16:49:12 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 17 Jul 2010 07:49:12 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <4C41A57A.80306@gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<4C41A57A.80306@gmail.com>
Message-ID: <AANLkTilYdsuq9429ANR-VCCuHR_pDh0eCAD_RIQOlK0p@mail.gmail.com>

Thanks, guys. See <http://tutoree7.pastebin.com/M1U00vtD>. It made the
1billion digits file in 213 seconds! And my laptop didn't begin to
choke. You made my day!

I'll consider all the binary info later.

Dick

From alan.gauld at btinternet.com  Sat Jul 17 20:06:00 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 17 Jul 2010 19:06:00 +0100
Subject: [Tutor] A file containing a string of 1 billion random digits.
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
Message-ID: <i1sre8$6de$1@dough.gmane.org>


"Richard D. Moores" <rdmoores at gmail.com> wrote

> amount of memory my laptop has (4 GB). So my question is, how can I 
> do
> this differently? I'm pretty brand new to opening and writing files.
> Here, I can't write many shorter lines, because the end result I 
> seek
> is one long string. But am I correct?

Others have answered that but I will ask, have you considered what
you will do with this 4G string once you have created it? You will not
be able to read it back into your memory in one piece so you will
need to process it in chunks.

It may be as well considering what you intend to do with it before
creating it? There may be a better representation.

Just a thought,

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



From lang at tharin.com  Sat Jul 17 20:23:14 2010
From: lang at tharin.com (Lang Hurst)
Date: Sat, 17 Jul 2010 11:23:14 -0700
Subject: [Tutor] Strange sqlite3 behavior
In-Reply-To: <4C417231.5050001@timgolden.me.uk>
References: <4C41574E.2070601@tharin.com> <4C417231.5050001@timgolden.me.uk>
Message-ID: <4C41F512.3090505@tharin.com>

On 07/17/2010 02:04 AM, Tim Golden wrote:
> On 17/07/2010 8:10 AM, Lang Hurst wrote:
>> I just had the weirdest issue with sqlite3.  I was trying to update a
>> field to "Active".  I have a little database of students and sometimes
>> they get sent to juvi, or just check out for a couple of months and show
>> back up.  Anyway, I wanted to just have a field that had either "Active"
>> or "Inactive".  I know, could go all boolean, but wanted to leave my
>> options open.
>>
>> Anyway, my code was along the lines of
>>
>>      UPDATE students SET active="Inactive" where id="123456"
>>
>>
>> That would work, but
>>
>>      UPDATE students SET active="Active" where id="123456"
>>
>>
>> wouldn't.  It wouldn't do anything, the field still held "Inactive".
>
> My guess -- without bothering to check the sqlite docs -- is that
> sqlite uses single quotes to delimit strings and double quotes to
> delimit column. Or at least that it can be set up to do that. If
> that is the case then "Active" is taken to refer to the column
> active and not to the string active. So you're just setting it
> to itself.
>
> Try it with 'Active' instead.
>
> TJG


Yep, you were correct.  Just ran that through sqlite3browser and any 
phrase seems to work with either single or double quotes, EXCEPT 
"Active".  'Active' works though.  Good call.  I worked around it, but 
damn that was driving me crazy last night.

-- 
There are no stupid questions, just stupid people.


From davea at ieee.org  Sat Jul 17 22:56:52 2010
From: davea at ieee.org (Dave Angel)
Date: Sat, 17 Jul 2010 16:56:52 -0400
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
Message-ID: <4C421914.9020401@ieee.org>

Richard D. Moores wrote:
> That's the goal of the latest version of my script at
> <http://tutoree7.pastebin.com/5XYaaNfp>. The best I've been able to do
> so far is a file with 800 million digits.
>
> But it seems the writing of 800 million digits is the limit for the
> amount of memory my laptop has (4 GB). So my question is, how can I do
> this differently? I'm pretty brand new to opening and writing files.
> Here, I can't write many shorter lines, because the end result I seek
> is one long string. But am I correct?
>
> I'd appreciate any advice.
>
> BTW line 29 was added after getting the outputs noted at the bottom of
> the script. Using close() does seem to shorten the time it takes for
> my laptop to become usable again, but it's not decisive. Sometimes I
> have to reboot in order to get healthy again. (64-bit Vista).
>
> BTW2 It's probably not obvious why the list comprehension (line 19)
> has random.choice(d) where d is '0123456789'. Without that, the random
> ints of 1000 digits would never begin with a '0'. So I give them a
> chance to by prefixing one random digit using choice(d), and cutting
> the length of the rest from 1000 to 999.
>
> Dick
>
>   
Your code is both far more complex than it need be, and inaccurate in 
the stated goal of producing random digits.

There's no need to try to have all the "digits" in memory at the same 
time.  As others have pointed out, since you're using write() method, 
there's no newline automatically added, so there's no problem in writing 
a few bytes at a time.

Your concern over a leading zero applies equally to two leading zeroes, 
or three, or whatever.  So instead of using str() to convert an int to a 
string, use string formatting.  Either the % operator or the format() 
method.  Just use a format that guarantees zero-filling to the same 
width field as the size limit you supplied.

So generate a number between 0 and 9999999999, or whatever, and convert 
that to a fixed width string possibly containing leading zeros.  Write 
the string out, and loop back around.

DaveA


From rdmoores at gmail.com  Sat Jul 17 22:58:47 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 17 Jul 2010 13:58:47 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <i1sre8$6de$1@dough.gmane.org>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<i1sre8$6de$1@dough.gmane.org>
Message-ID: <AANLkTim88ERzhUlFpMD1QLM89uni3OhhC1KUsYTrtcu8@mail.gmail.com>

On Sat, Jul 17, 2010 at 11:06, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Richard D. Moores" <rdmoores at gmail.com> wrote
>
>> amount of memory my laptop has (4 GB). So my question is, how can I do
>> this differently? I'm pretty brand new to opening and writing files.
>> Here, I can't write many shorter lines, because the end result I seek
>> is one long string. But am I correct?
>
> Others have answered that but I will ask, have you considered what
> you will do with this 4G string once you have created it?

Windows Explorer tells me it is 976,563 KB.

> You will not
> be able to read it back into your memory in one piece so you will
> need to process it in chunks.

Yes, that's true. Here's what I'm doing with a 200-million-digit
string: <http://tutoree7.pastebin.com/rJ1naffZ>. But this script with
a 500 million string already causes a memory problem, and 1 billion is
impossible. If I processed in chunks, they would need to overlap
slightly, because the sequences to be found, such as 05251896 (my
father's birth date) could overlap the boundary between 2 neighboring
chunks, and thus not be located. That's about as far as I've got in
thinking about the problem.

> It may be as well considering what you intend to do with it before
> creating it? There may be a better representation.

Now that you see what I want to do with 1 billion random digits,
please give me your suggestion(s). As I mentioned before, I'm very new
to reading from and writing to files.

I think the project is much more interesting/satisfying, though
technically almost identical, when locating sequences of digits in pi.
I have a 100-million-digit file for this (thanks to gmpy.pi()), but
haven't tried for anything bigger. Here's the script that handles
searches in the mantissa of pi:
<http://tutoree7.pastebin.com/3mqCNgQJ>. I've put the 1 million digits
of pi on my website in the Pi directory at <http://www.rcblue.com/Pi/>
should anyone want to try this out. I'm not sure what my downloading
limit is, so I may not leave the file up there more than 24 hours.

Dick

From amartin7211 at gmail.com  Sat Jul 17 23:11:19 2010
From: amartin7211 at gmail.com (Andrew Martin)
Date: Sat, 17 Jul 2010 17:11:19 -0400
Subject: [Tutor] Return error message for my script in Blender
Message-ID: <AANLkTikpyQcYV7ZqP5hmVgb872r2F4RmHAo2DhXBI6vq@mail.gmail.com>

I am new to Blender and Python (2.6 on vista) and was trying to follow a
tutorial in the book Blender 2.49 Scripting by Michel Anders. I was trying
to write a script that would create a user interface where the user could
select various aspect of an insect and the code would create a polygonal
bug. However, when I copied code exactly from the book, I got an error
saying "'return' outside function". Here is the code I had in the text
editor:


#!BPY

import Blender
import mymesh2

Draw = Blender.Draw
THORAXSEGMENTS = Draw.Create(3)
TAILSEGMENTS = Draw.Create(5)
LEGSEGMENTS = Draw.Create(2)
WINGSEGMENTS = Draw.Create(2)
EYESIZE = Draw.Create(1.0)
TAILTAPER = Draw.Create(0.9)

if not Draw.PupBlock('Add CreepyCrawly', [\
('Thorax segments:'  , THORAXSEGMENTS, 2,  50,
    'Number of thorax segments'),
('Tail segments:' , TAILSEGMENTS, 0,  50, 'Number of tail segments'),
('Leg segments:' , LEGSEGMENTS, 2,  10,
    'Number of thorax segments with legs'),
('Wing segments:' , WINGSEGMENTS, 0,  10,
    'Number of thorax segments with wings'),
('Eye size:' , EYESIZE, 0.1,10, 'Size of the eyes'),
('Tail taper:' , TAILTAPER, 0.1,10,
    'Taper fraction of each tail segment'),]):
     return


Anybody know why I keep getting this error?

Thanks a lot
amartin7211
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100717/af788992/attachment.html>

From rdmoores at gmail.com  Sat Jul 17 23:48:06 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 17 Jul 2010 14:48:06 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <4C421914.9020401@ieee.org>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<4C421914.9020401@ieee.org>
Message-ID: <AANLkTimLbrCeYKfgkvtqmsFc0ay6cHxwTDen4ZVDeGhb@mail.gmail.com>

On Sat, Jul 17, 2010 at 13:56, Dave Angel <davea at ieee.org> wrote:

> Your code is both far more complex than it need be, and inaccurate in the
> stated goal of producing random digits.

Dave, please see the code I posted in this thread more recently,
<http://tutoree7.pastebin.com/M1U00vtD>.

> There's no need to try to have all the "digits" in memory at the same time.
> ?As others have pointed out, since you're using write() method, there's no
> newline automatically added, so there's no problem in writing a few bytes at
> a time.

I write a 1000 at a time.

> Your concern over a leading zero applies equally to two leading zeroes, or
> three, or whatever.

I don't think so. Look again at my function, randIntOfGivenLength().
Try a for loop with it, say with randIntOfGivenLength(9) and looping
100 times:

for x in range(100):
     n = randIntOfGivenLength(9)
     n = str(n)
     print(n)

You'll see that all strings have 9 digits. The problem is that none of
them begin with "0". These are just strings of almost-random digits,
and in the script I give the 1st digit a chance to be a "0" by
prepending a digit -- just one -- chosen by random.choice() from the
string "0123456789". There's no need for zero-filling. I do agree that
it would be good to eliminate the need to use str(). I'll look at the
first part of your formatting suggestion, and skip the zero-filling.

> ?So instead of using str() to convert an int to a
> string, use string formatting. ?Either the % operator or the format()
> method. ?Just use a format that guarantees zero-filling to the same width
> field as the size limit you supplied.
>
> So generate a number between 0 and 9999999999,

That would be between 1,000,000,000 and 9,999,999,999 .

Dick

> or whatever, and convert that
> to a fixed width string possibly containing leading zeros. ?Write the string
> out, and loop back around.
>
> DaveA

From hugo.yoshi at gmail.com  Sun Jul 18 00:07:45 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sun, 18 Jul 2010 00:07:45 +0200
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTimLbrCeYKfgkvtqmsFc0ay6cHxwTDen4ZVDeGhb@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<4C421914.9020401@ieee.org>
	<AANLkTimLbrCeYKfgkvtqmsFc0ay6cHxwTDen4ZVDeGhb@mail.gmail.com>
Message-ID: <AANLkTilgLWw-wzCcXYQ4g1i7CdSe5VqJIRKRrE7b6TOo@mail.gmail.com>

On Sat, Jul 17, 2010 at 11:48 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
> On Sat, Jul 17, 2010 at 13:56, Dave Angel <davea at ieee.org> wrote:
>> Your concern over a leading zero applies equally to two leading zeroes, or
>> three, or whatever.
>
> I don't think so. Look again at my function, randIntOfGivenLength().
> Try a for loop with it, say with randIntOfGivenLength(9) and looping
> 100 times:
>
> for x in range(100):
> ? ? n = randIntOfGivenLength(9)
> ? ? n = str(n)
> ? ? print(n)
>
> You'll see that all strings have 9 digits. The problem is that none of
> them begin with "0". These are just strings of almost-random digits,
> and in the script I give the 1st digit a chance to be a "0" by
> prepending a digit -- just one -- chosen by random.choice() from the
> string "0123456789".
>

This is great, but now your *second* digit will never be zero. So your
strings are still "almost" random.

<rant> Look, randomness is complicated. It's crap like this that trips
up even cryptographers all the time. I know you won't need your digits
for security or anything, but if you're concerned that the first digit
of a sequence is never zero, you should be equally concerned by the
second digit not being zero. It's the same amount of non-randomness,
and your 'solution' just moves the problem around, it doesn't solve
anything. </rant>

Hugo

P.S.: I just thought of this: how about generating numbers that are
one digit too long, and removing the first digit instead of adding an
extra one? It just gets rid of the digit exhibiting non-randomness
altogether. (disclaimer: IANA cryptanalyst, so there may be equally
many things wrong with this)

From alan.gauld at btinternet.com  Sun Jul 18 00:36:06 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Sat, 17 Jul 2010 15:36:06 -0700 (PDT)
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTim88ERzhUlFpMD1QLM89uni3OhhC1KUsYTrtcu8@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<i1sre8$6de$1@dough.gmane.org>
	<AANLkTim88ERzhUlFpMD1QLM89uni3OhhC1KUsYTrtcu8@mail.gmail.com>
Message-ID: <63679.44550.qm@web86705.mail.ird.yahoo.com>

> Now that you see what I want to do with 1 billion random 
digits,
> please give me your suggestion(s). As I mentioned 
before, 
> I'm very new to reading from and writing to files.

The way old text editors used to do this - in the days when we only had 16K RAM etc!
was to use buffers and pages. Let's say you have a 100K buffer size and read in the 
first buffer full of text. When you get down to say 75K you delete the first 50K and 
load the next 50K from the file. Your cursor is now 25K into a new set of 100K.

This allows you to page back a certain amount and page forward a lot. And so 
you progress losing 50% from top or bottom and loading the next/previous chunk 
into RAM. Its non-trivial to get right but in your case you are only looking to 
sequentially process so you only need to look forward so not quite so bad...

You need markers to keep your location and other markers to keep track of 
the buffers location within the file.

If you really are only doing sequential processing you can dispense with 
the buffer/pages and just read small chunks such that you always have two 
in memory at once. The chunks might only be a few Kb in size depending 
on the longest sequence you are looking for (a chunk of twice that size is 
a good guide)

The seek() tell() and read() methods are your friends for this kind of work

 
Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/

From rdmoores at gmail.com  Sun Jul 18 00:39:37 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 17 Jul 2010 15:39:37 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTilgLWw-wzCcXYQ4g1i7CdSe5VqJIRKRrE7b6TOo@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<4C421914.9020401@ieee.org>
	<AANLkTimLbrCeYKfgkvtqmsFc0ay6cHxwTDen4ZVDeGhb@mail.gmail.com> 
	<AANLkTilgLWw-wzCcXYQ4g1i7CdSe5VqJIRKRrE7b6TOo@mail.gmail.com>
Message-ID: <AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com>

On Sat, Jul 17, 2010 at 15:07, Hugo Arts <hugo.yoshi at gmail.com> wrote:
> On Sat, Jul 17, 2010 at 11:48 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
>> On Sat, Jul 17, 2010 at 13:56, Dave Angel <davea at ieee.org> wrote:
>>> Your concern over a leading zero applies equally to two leading zeroes, or
>>> three, or whatever.
>>
>> I don't think so. Look again at my function, randIntOfGivenLength().
>> Try a for loop with it, say with randIntOfGivenLength(9) and looping
>> 100 times:
>>
>> for x in range(100):
>> ? ? n = randIntOfGivenLength(9)
>> ? ? n = str(n)
>> ? ? print(n)
>>
>> You'll see that all strings have 9 digits. The problem is that none of
>> them begin with "0". These are just strings of almost-random digits,
>> and in the script I give the 1st digit a chance to be a "0" by
>> prepending a digit -- just one -- chosen by random.choice() from the
>> string "0123456789".
>>
>
> This is great, but now your *second* digit will never be zero. So your
> strings are still "almost" random.

Aw, you're right. Just as I was feeling pretty good about myself.

> <rant> Look, randomness is complicated. It's crap like this that trips
> up even cryptographers all the time. I know you won't need your digits
> for security or anything, but if you're concerned that the first digit
> of a sequence is never zero, you should be equally concerned by the
> second digit not being zero. It's the same amount of non-randomness,
> and your 'solution' just moves the problem around, it doesn't solve
> anything. </rant>
>
> Hugo
>
> P.S.: I just thought of this: how about generating numbers that are
> one digit too long, and removing the first digit instead of adding an
> extra one? It just gets rid of the digit exhibiting non-randomness
> altogether. (disclaimer: IANA cryptanalyst, so there may be equally
> many things wrong with this)

Looks good to me. I'll do it. And post back.

Thanks, Hugo.

Dick

From rdmoores at gmail.com  Sun Jul 18 01:23:15 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 17 Jul 2010 16:23:15 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<4C421914.9020401@ieee.org>
	<AANLkTimLbrCeYKfgkvtqmsFc0ay6cHxwTDen4ZVDeGhb@mail.gmail.com> 
	<AANLkTilgLWw-wzCcXYQ4g1i7CdSe5VqJIRKRrE7b6TOo@mail.gmail.com> 
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com>
Message-ID: <AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com>

On Sat, Jul 17, 2010 at 15:39, Richard D. Moores <rdmoores at gmail.com> wrote:
> On Sat, Jul 17, 2010 at 15:07, Hugo Arts <hugo.yoshi at gmail.com> wrote:

>> P.S.: I just thought of this: how about generating numbers that are
>> one digit too long, and removing the first digit instead of adding an
>> extra one? It just gets rid of the digit exhibiting non-randomness
>> altogether. (disclaimer: IANA cryptanalyst, so there may be equally
>> many things wrong with this)
>
> Looks good to me. I'll do it. And post back.

Done. See <http://tutoree7.pastebin.com/9BMYZ08z>.

Dick

From bgailer at gmail.com  Sun Jul 18 02:01:00 2010
From: bgailer at gmail.com (bob gailer)
Date: Sat, 17 Jul 2010 20:01:00 -0400
Subject: [Tutor] Return error message for my script in Blender
In-Reply-To: <AANLkTikpyQcYV7ZqP5hmVgb872r2F4RmHAo2DhXBI6vq@mail.gmail.com>
References: <AANLkTikpyQcYV7ZqP5hmVgb872r2F4RmHAo2DhXBI6vq@mail.gmail.com>
Message-ID: <4C42443C.5030402@gmail.com>

On 7/17/2010 5:11 PM, Andrew Martin wrote:
> I am new to Blender and Python (2.6 on vista) and was trying to follow 
> a tutorial in the book Blender 2.49 Scripting by Michel Anders. I was 
> trying to write a script that would create a user interface where the 
> user could select various aspect of an insect and the code would 
> create a polygonal bug. However, when I copied code exactly from the 
> book, I got an error saying "'return' outside function". Here is the 
> code I had in the text editor:
>
>
> #!BPY
>
> import Blender
> import mymesh2
>
> Draw = Blender.Draw
> THORAXSEGMENTS = Draw.Create(3)
> TAILSEGMENTS = Draw.Create(5)
> LEGSEGMENTS = Draw.Create(2)
> WINGSEGMENTS = Draw.Create(2)
> EYESIZE = Draw.Create(1.0)
> TAILTAPER = Draw.Create(0.9)
>
> if not Draw.PupBlock('Add CreepyCrawly', [\
> ('Thorax segments:'  , THORAXSEGMENTS, 2,  50,
>     'Number of thorax segments'),
> ('Tail segments:' , TAILSEGMENTS, 0,  50, 'Number of tail segments'),
> ('Leg segments:' , LEGSEGMENTS, 2,  10,
>     'Number of thorax segments with legs'),
> ('Wing segments:' , WINGSEGMENTS, 0,  10,
>     'Number of thorax segments with wings'),
> ('Eye size:' , EYESIZE, 0.1,10, 'Size of the eyes'),
> ('Tail taper:' , TAILTAPER, 0.1,10,
>     'Taper fraction of each tail segment'),]):
>      return
>
>
> Anybody know why I keep getting this error?

The return statement is not in a function. What else can we say. Either 
you copied incorrectly or there is a problem with the book.

Do you understand?

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From rdmoores at gmail.com  Sun Jul 18 02:19:06 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 17 Jul 2010 17:19:06 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <63679.44550.qm@web86705.mail.ird.yahoo.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<i1sre8$6de$1@dough.gmane.org>
	<AANLkTim88ERzhUlFpMD1QLM89uni3OhhC1KUsYTrtcu8@mail.gmail.com> 
	<63679.44550.qm@web86705.mail.ird.yahoo.com>
Message-ID: <AANLkTikEr4OM9gR2IiAhfUdA_7rMl9cek8OzU5DbR8AK@mail.gmail.com>

On Sat, Jul 17, 2010 at 15:36, ALAN GAULD <alan.gauld at btinternet.com> wrote:
>> Now that you see what I want to do with 1 billion random
> digits,
>> please give me your suggestion(s). As I mentioned
> before,
>> I'm very new to reading from and writing to files.
>
> The way old text editors used to do this - in the days when we only had 16K RAM etc!
> was to use buffers and pages. Let's say you have a 100K buffer size and read in the
> first buffer full of text. When you get down to say 75K you delete the first 50K and
> load the next 50K from the file. Your cursor is now 25K into a new set of 100K.
>
> This allows you to page back a certain amount and page forward a lot. And so
> you progress losing 50% from top or bottom and loading the next/previous chunk
> into RAM. Its non-trivial to get right but in your case you are only looking to
> sequentially process so you only need to look forward so not quite so bad...
>
> You need markers to keep your location and other markers to keep track of
> the buffers location within the file.
>
> If you really are only doing sequential processing you can dispense with
> the buffer/pages and just read small chunks such that you always have two
> in memory at once. The chunks might only be a few Kb in size depending
> on the longest sequence you are looking for (a chunk of twice that size is
> a good guide)

The longest sequence I can imagine finding with, say, a .1 probability
is less than 30 bytes, I'd guess.

To quote myself from my earlier reply to you:

"If I processed in chunks, they would need to overlap
slightly, because the sequences to be found, such as 05251896 (my
father's birth date) could overlap the boundary between 2 neighboring
chunks, and thus not be located."

I don't fully understand your "you always have two [chunks] in memory
at once". Does that take care of the overlap I think I need? I don't
want you or anyone to give me the the whole answer, but could you
clarify a bit about keeping 2 chunks in memory? Let's say the chunks,
in order, and without overlap, are A, B, C, D, E, ...  So I'd have AB
to search, then BC, then CD, then DE, ... ? But then what if I find an
instance of, say, my father's birthdate in B when searching AB. Then
I'd find the same instance again in BC. How do I prevent that from
counting as 2 instances?

> The seek() tell() and read() methods are your friends for this kind of work.

I hope they're not shy about telling me their secrets. Would your
tutorial be a good place to start to inquire of them?

There's this table in chapter 9 of Learning Python, 4th ed., but no
tell(). And a search on  'tell('  gets not a hit in the whole book
(the PDF). Is tell() a Python 2.x thing? It's a built-in for 2.x
(<http://docs.python.org/library/stdtypes.html?highlight=tell#file.tell>),
but not, it seems, for 3.x. I'm not complaining -- just sayin'.

Table 9-2. Common file operations
Operation Interpretation
output = open(r'C:\spam', 'w') Create output file ('w' means write)
input = open('data', 'r') Create input file ('r' means read)
input = open('data') Same as prior line ('r' is the default)
aString = input.read() Read entire file into a single string
aString = input.read(N) Read up to next N characters (or bytes) into a string
aString = input.readline() Read next line (including \n newline) into a string
aList = input.readlines() Read entire file into list of line strings (with \n)
output.write(aString) Write a string of characters (or bytes) into file
output.writelines(aList) Write all line strings in a list into file
output.close() Manual close (done for you when file is collected)
output.flush() Flush output buffer to disk without closing
anyFile.seek(N) Change file position to offset N for next operation
for line in open('data'): use line File iterators read line by line
open('f.txt', encoding='latin-1') Python 3.0 Unicode text files (str strings)
open('f.bin', 'rb') Python 3.0 binary bytes files (bytes strings)

Thanks again, Alan.

Dick

From rdmoores at gmail.com  Sun Jul 18 02:24:19 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 17 Jul 2010 17:24:19 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTikEr4OM9gR2IiAhfUdA_7rMl9cek8OzU5DbR8AK@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<i1sre8$6de$1@dough.gmane.org>
	<AANLkTim88ERzhUlFpMD1QLM89uni3OhhC1KUsYTrtcu8@mail.gmail.com> 
	<63679.44550.qm@web86705.mail.ird.yahoo.com>
	<AANLkTikEr4OM9gR2IiAhfUdA_7rMl9cek8OzU5DbR8AK@mail.gmail.com>
Message-ID: <AANLkTikGiskQyO5l5EKDnHYOF_tAA0LF3vgIWbXoYDC7@mail.gmail.com>

Alan,

I should have added that file.seek and file.read don't show in the 3.x
docs either.

Dick

From hugo.yoshi at gmail.com  Sun Jul 18 02:39:27 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sun, 18 Jul 2010 02:39:27 +0200
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTikGiskQyO5l5EKDnHYOF_tAA0LF3vgIWbXoYDC7@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<i1sre8$6de$1@dough.gmane.org>
	<AANLkTim88ERzhUlFpMD1QLM89uni3OhhC1KUsYTrtcu8@mail.gmail.com> 
	<63679.44550.qm@web86705.mail.ird.yahoo.com>
	<AANLkTikEr4OM9gR2IiAhfUdA_7rMl9cek8OzU5DbR8AK@mail.gmail.com> 
	<AANLkTikGiskQyO5l5EKDnHYOF_tAA0LF3vgIWbXoYDC7@mail.gmail.com>
Message-ID: <AANLkTimtfZ5V2kcYhkE2cbxQF47PIU3cffat1wgMqL38@mail.gmail.com>

On Sun, Jul 18, 2010 at 2:24 AM, Richard D. Moores <rdmoores at gmail.com> wrote:
> Alan,
>
> I should have added that file.seek and file.read don't show in the 3.x
> docs either.
>

You just need to know where to look:

http://docs.python.org/py3k/library/io.html#io.IOBase.tell

read and seek are in there as well. There is no more file class in
3.x, the io module takes care of all that. The documentation for the
open() function mentions all of this.

Hugo

From steve at pearwood.info  Sun Jul 18 03:01:32 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 18 Jul 2010 11:01:32 +1000
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com>
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com>
Message-ID: <201007181101.33483.steve@pearwood.info>

Do you care about speed? If this is a script that just needs to run 
once, it seems to me that the simplest, easiest to read solution is:

import random
def random_digit():
    return "0123456789"[random.randrange(10)]

f = open('rand_digits.txt', 'w')
for i in xrange(10**9):
    f.write(random_digit())

f.close()


This is, of course, horribly inefficient -- it generates digits one at a 
time, and worse, it writes them one at a time. I got bored waiting for 
it to finish after 20 minutes (at which time it was about 10% of the 
way through), but you could let it run in the background for as long as 
it takes.

If speed does matter, the first improvement is to generate larger 
streams of random digits at once. An even bigger improvement is to cut 
down on the number of disk-writes -- hard drives are a thousand times 
slower than RAM, so the more often you write to the disk, the worse off 
you are.


import random
def random_digits(n):
    "Return n random digits with one call to random."
    return "%0*d" % (n, random.randrange(10**n))

f = open('rand_digits.txt', 'w')
for i in xrange(1000):
    buffer = [random_digits(10) for j in xrange(100000)]
    f.write(''.join(buffer))

f.close()

On my not-even-close-to-high-end PC, this generates one billion digits 
in 22 minutes:

[steve at sylar python]$ time python randdigits.py

real    22m31.205s
user    20m18.546s
sys     0m7.675s
[steve at sylar python]$ ls -l rand_digits.txt
-rw-rw-r-- 1 steve steve 1000000000 2010-07-18 11:00 rand_digits.txt


Having generated the digits, it might be useful to look for deviations 
from randomness. There should be approximately equal numbers of each 
digit (100,000,000 each of 0, 1, 2, ..., 9), of each digraph 
(10,000,000 each of 00, 01, 02, ..., 98, 99), trigraphs (1,000,000 each 
of 000, ..., 999) and so forth.

The interesting question is, if you measure a deviation from the 
equality (and you will), is it statistically significant? If so, it is 
because of a problem with the random number generator, or with my 
algorithm for generating the sample digits?



-- 
Steven D'Aprano

From rdmoores at gmail.com  Sun Jul 18 03:01:42 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 17 Jul 2010 18:01:42 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTimtfZ5V2kcYhkE2cbxQF47PIU3cffat1wgMqL38@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<i1sre8$6de$1@dough.gmane.org>
	<AANLkTim88ERzhUlFpMD1QLM89uni3OhhC1KUsYTrtcu8@mail.gmail.com> 
	<63679.44550.qm@web86705.mail.ird.yahoo.com>
	<AANLkTikEr4OM9gR2IiAhfUdA_7rMl9cek8OzU5DbR8AK@mail.gmail.com> 
	<AANLkTikGiskQyO5l5EKDnHYOF_tAA0LF3vgIWbXoYDC7@mail.gmail.com> 
	<AANLkTimtfZ5V2kcYhkE2cbxQF47PIU3cffat1wgMqL38@mail.gmail.com>
Message-ID: <AANLkTinl6SrqVsSpV9fb_7D6TKlmWq1z11Oy39KYtLpg@mail.gmail.com>

On Sat, Jul 17, 2010 at 17:39, Hugo Arts <hugo.yoshi at gmail.com> wrote:
> On Sun, Jul 18, 2010 at 2:24 AM, Richard D. Moores <rdmoores at gmail.com> wrote:
>> Alan,
>>
>> I should have added that file.seek and file.read don't show in the 3.x
>> docs either.
>>
>
> You just need to know where to look:
>
> http://docs.python.org/py3k/library/io.html#io.IOBase.tell
>
> read and seek are in there as well. There is no more file class in
> 3.x, the io module takes care of all that. The documentation for the
> open() function mentions all of this.

Ah. Thanks again, Hugo. Looks like tough going for me for a couple of
days. Months?

Dick

From steve at pearwood.info  Sun Jul 18 03:11:40 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 18 Jul 2010 11:11:40 +1000
Subject: [Tutor] Return error message for my script in Blender
In-Reply-To: <AANLkTikpyQcYV7ZqP5hmVgb872r2F4RmHAo2DhXBI6vq@mail.gmail.com>
References: <AANLkTikpyQcYV7ZqP5hmVgb872r2F4RmHAo2DhXBI6vq@mail.gmail.com>
Message-ID: <201007181111.40566.steve@pearwood.info>

On Sun, 18 Jul 2010 07:11:19 am Andrew Martin wrote:
> I am new to Blender and Python (2.6 on vista) and was trying to
> follow a tutorial in the book Blender 2.49 Scripting by Michel
> Anders. I was trying to write a script that would create a user
> interface where the user could select various aspect of an insect and
> the code would create a polygonal bug. However, when I copied code
> exactly from the book, I got an error saying "'return' outside
> function". Here is the code I had in the text editor:
[...]
> Anybody know why I keep getting this error?

The return statement can only be inside a function. Here is an example:

def f():
    return "This is inside a function."

You have it outside a function, just like the error message says.


-- 
Steven D'Aprano

From rdmoores at gmail.com  Sun Jul 18 03:51:17 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 17 Jul 2010 18:51:17 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <201007181101.33483.steve@pearwood.info>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com> 
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com> 
	<201007181101.33483.steve@pearwood.info>
Message-ID: <AANLkTilC_X2q0sbXqzgC4JEUJLQST_Poq92SP8O8Vyy5@mail.gmail.com>

On Sat, Jul 17, 2010 at 18:01, Steven D'Aprano <steve at pearwood.info> wrote:
> Do you care about speed? If this is a script that just needs to run
> once, it seems to me that the simplest, easiest to read solution is:
>
> import random
> def random_digit():
> ? ?return "0123456789"[random.randrange(10)]
>
> f = open('rand_digits.txt', 'w')
> for i in xrange(10**9):
> ? ?f.write(random_digit())
>
> f.close()
>
>
> This is, of course, horribly inefficient -- it generates digits one at a
> time, and worse, it writes them one at a time. I got bored waiting for
> it to finish after 20 minutes (at which time it was about 10% of the
> way through), but you could let it run in the background for as long as
> it takes.
>
> If speed does matter, the first improvement is to generate larger
> streams of random digits at once. An even bigger improvement is to cut
> down on the number of disk-writes -- hard drives are a thousand times
> slower than RAM, so the more often you write to the disk, the worse off
> you are.
>
>
> import random
> def random_digits(n):
> ? ?"Return n random digits with one call to random."
> ? ?return "%0*d" % (n, random.randrange(10**n))
>
> f = open('rand_digits.txt', 'w')
> for i in xrange(1000):
> ? ?buffer = [random_digits(10) for j in xrange(100000)]
> ? ?f.write(''.join(buffer))
>
> f.close()
>
> On my not-even-close-to-high-end PC, this generates one billion digits
> in 22 minutes:
>
> [steve at sylar python]$ time python randdigits.py
>
> real ? ?22m31.205s
> user ? ?20m18.546s
> sys ? ? 0m7.675s
> [steve at sylar python]$ ls -l rand_digits.txt
> -rw-rw-r-- 1 steve steve 1000000000 2010-07-18 11:00 rand_digits.txt

My <http://tutoree7.pastebin.com/9BMYZ08z> took 218 secs.

> Having generated the digits, it might be useful to look for deviations
> from randomness. There should be approximately equal numbers of each
> digit (100,000,000 each of 0, 1, 2, ..., 9), of each digraph
> (10,000,000 each of 00, 01, 02, ..., 98, 99), trigraphs (1,000,000 each
> of 000, ..., 999) and so forth.

Yes. I'll do some checking. Thanks for the tips.
>
> The interesting question is, if you measure a deviation from the
> equality (and you will), is it statistically significant? If so, it is
> because of a problem with the random number generator, or with my
> algorithm for generating the sample digits?

Ah. Can't wait to see what turns up.

Thanks, Steve.

Dick

From rabidpoobear at gmail.com  Sun Jul 18 07:55:20 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 18 Jul 2010 00:55:20 -0500
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTikEr4OM9gR2IiAhfUdA_7rMl9cek8OzU5DbR8AK@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<i1sre8$6de$1@dough.gmane.org>
	<AANLkTim88ERzhUlFpMD1QLM89uni3OhhC1KUsYTrtcu8@mail.gmail.com>
	<63679.44550.qm@web86705.mail.ird.yahoo.com>
	<AANLkTikEr4OM9gR2IiAhfUdA_7rMl9cek8OzU5DbR8AK@mail.gmail.com>
Message-ID: <F6E47861-C904-43FA-9B0B-8F49A886B08A@gmail.com>


On Jul 17, 2010, at 7:19 PM, "Richard D. Moores" <rdmoores at gmail.com> wrote:

> I don't fully understand your "you always have two [chunks] in memory
> at once". Does that take care of the overlap I think I need? I don't
> want you or anyone to give me the the whole answer, but could you
> clarify a bit about keeping 2 chunks in memory? Let's say the chunks,
> in order, and without overlap, are A, B, C, D, E, ...  So I'd have AB
> to search, then BC, then CD, then DE, ... ? But then what if I find an
> instance of, say, my father's birthdate in B when searching AB. Then
> I'd find the same instance again in BC. How do I prevent that from
> counting as 2 instances?

Imagine you have a series of Buildings in a block, and you are checking to see if a series of 5 windows in a row is on ( even between buildings). You start at one end of the block and you check the first five windows. If they are all on, you have found a match. If not, you move forward one window. Now repeat. After a few repetitions you will end up at the border between two buildings, and after a few more you will be looking exclusively at the 2nd building. Then after a few more you will be looking at the 3rd building and so on.

But are you ever looking at more than one building at a time? Yea but only adjacent buildings and only for 4 steps. Once, when you have 4 windows from the first, 1 from the second, again for 3 windows from the first, then 2 and then 1.

The way this translates into an algorithm is that instead of discarding your old set of data as soon as you need to load another set, you hold onto it long enough to get all the way engaged with that second set, and from there you can free up the previous block's memory and move forward. And since you are using a "sliding window" approach you shouldn't ever find one result twice. Although note that if you overlap your searches as I said earlier, you can run into some matching situations that are interesting. Say you search for 55 and your string is 1827355513. You'll find 55 twice even though there are only 3 fives in the search string. Just something to keep in mind.

Hope that helps!
-luke
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100718/71bae76a/attachment-0001.html>

From alan.gauld at btinternet.com  Sun Jul 18 08:29:07 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 18 Jul 2010 07:29:07 +0100
Subject: [Tutor] A file containing a string of 1 billion random digits.
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<i1sre8$6de$1@dough.gmane.org><AANLkTim88ERzhUlFpMD1QLM89uni3OhhC1KUsYTrtcu8@mail.gmail.com>
	<63679.44550.qm@web86705.mail.ird.yahoo.com>
	<AANLkTikEr4OM9gR2IiAhfUdA_7rMl9cek8OzU5DbR8AK@mail.gmail.com>
Message-ID: <i1u6vj$6tk$1@dough.gmane.org>

"Richard D. Moores" <rdmoores at gmail.com> wrote

> I don't fully understand your "you always have two [chunks] in 
> memory
> at once". Does that take care of the overlap I think I need? I don't
> want you or anyone to give me the the whole answer, but could you
> clarify a bit about keeping 2 chunks in memory?

Luke gave a good illustration, I'll try to be a bit more clear than
my previous explanation.

Think of the buffer as being a window into the file.
We read the file in chunks and load these into the buffer.
Lets say 3 chunks per buffer.
When we first start up we read chunks 1,2,3 into the buffer.
We start processing chunk 1, then move into chunk 2. By the
time we are 50% through chunk 2 we no longer need chunk 1
so we move it out of memory and read in chunk 4. We move
chunk 2 & 3 to the top of the buffer and append chunk 4.
Now we continue processing until we hit chunk 3 and go
down 50%, we no longer need chunk 2 so delete it and
read chunk 5, move 3 and 4 to the top and load chunk 5
into the buffer.

And so it goes on.
The buffer is a continuous bit of memory holding 3 chunks
of data contiguously so you can process over the boundaries
but your program only has to store 3 chunks worth at a time.

I hope thats clearer.

It might help to think how this worked for an old style
text editor. The chunks represent a screens worth of display.
You only need to display the middle chunk. As you cursor
off the bottom of the screen you pull up the next chunk
in memory (and in the background read the next again
from file and lose the top chunk). This resulted in a user
experience that looked like the whole file was in memory
but in fact only about 6Kb was (3 screens full).

HTH,


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



From steve at pearwood.info  Sun Jul 18 09:20:21 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 18 Jul 2010 17:20:21 +1000
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTilC_X2q0sbXqzgC4JEUJLQST_Poq92SP8O8Vyy5@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<201007181101.33483.steve@pearwood.info>
	<AANLkTilC_X2q0sbXqzgC4JEUJLQST_Poq92SP8O8Vyy5@mail.gmail.com>
Message-ID: <201007181720.23088.steve@pearwood.info>

On Sun, 18 Jul 2010 11:51:17 am Richard D. Moores wrote:
[...]
> > On my not-even-close-to-high-end PC, this generates one billion
> > digits in 22 minutes:

> My <http://tutoree7.pastebin.com/9BMYZ08z> took 218 secs.

Lucky for some :)

Your version, on my machine, took 16 minutes, an improvement over my 
initial trial, but still much slower than your PC. 

I had initially thought that I was seeing the difference between local 
hard drive access and the speed of my network, as my home directory is 
on a remote machine, but I don't think this is the case. I modified 
your version to write to a file on the local hard drive instead of a 
remote file, but the speed hardly changed: 15 minutes instead of 16. 
The best I was able to get my version down to is 14 minutes, so I guess 
I just have to accept that my PC is seven times slower than yours :)


-- 
Steven D'Aprano

From rdmoores at gmail.com  Sun Jul 18 10:49:39 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sun, 18 Jul 2010 01:49:39 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <201007181101.33483.steve@pearwood.info>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com> 
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com> 
	<201007181101.33483.steve@pearwood.info>
Message-ID: <AANLkTikWdpxwuwDPhY5mLOfvCBnHvLn-maxiK77RM5gv@mail.gmail.com>

On Sat, Jul 17, 2010 at 18:01, Steven D'Aprano <steve at pearwood.info> wrote:

> Having generated the digits, it might be useful to look for deviations
> from randomness. There should be approximately equal numbers of each
> digit (100,000,000 each of 0, 1, 2, ..., 9), of each digraph
> (10,000,000 each of 00, 01, 02, ..., 98, 99), trigraphs (1,000,000 each
> of 000, ..., 999) and so forth.

I've been doing a bit of that. I found approx. equal numbers of each
digit (including the zeros :) ). Then I thought I'd look at pairs of
the same digit ('00', '11, and so on). See my
<http://tutoree7.pastebin.com/S9JzmmtY>. The results for the 1 billion
file start at line 78, and look good to me. I might try trigraphs
where the 2nd digit is 2 more than the first, and the third 2 more
than the 2nd. E.g. '024', '135', '791', '802'. Or maybe I've had
enough. BTW Steve, my script avoids the problem you mentioned, of
counting 2 '55's in a '555' string. I get only one, but 2 in '5555'.
See line 18, in the while loop.

I was surprised that I could read in the whole billion file with one
gulp without running out of memory. Memory usage went to 80% (from the
usual 35%), but no higher except at first, when I saw 98% for a few
seconds, and then a drop to 78-80% where it stayed.

> The interesting question is, if you measure a deviation from the
> equality (and you will), is it statistically significant? If so, it is
> because of a problem with the random number generator, or with my
> algorithm for generating the sample digits?

I was pretty good at statistics long ago -- almost became a
statistician -- but I've pretty much lost what I had. Still, I'd bet
that the deviations I've seen so far are not significant.

Thanks for the stimulating challenge, Steve.

Dick

From steve at pearwood.info  Sun Jul 18 11:26:07 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 18 Jul 2010 19:26:07 +1000
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTikWdpxwuwDPhY5mLOfvCBnHvLn-maxiK77RM5gv@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<201007181101.33483.steve@pearwood.info>
	<AANLkTikWdpxwuwDPhY5mLOfvCBnHvLn-maxiK77RM5gv@mail.gmail.com>
Message-ID: <201007181926.08498.steve@pearwood.info>

On Sun, 18 Jul 2010 06:49:39 pm Richard D. Moores wrote:

> I might try 
> trigraphs where the 2nd digit is 2 more than the first, and the third
> 2 more than the 2nd. E.g. '024', '135', '791', '802'. 

Why the restriction? There's only 1000 different trigraphs (10*10*10), 
which is nothing.


> Or maybe I've 
> had enough. BTW Steve, my script avoids the problem you mentioned, of
> counting 2 '55's in a '555' string. I get only one, but 2 in '5555'.

Huh? What problem did I mention? 

Taking the string '555', you should get two digraphs: 55_ and _55. 
In '5555' you should get three: 55__, _55_, __55. I'd do something like 
this (untested):

trigraphs = {}
f = open('digits')
trigraph = f.read(3)  # read the first three digits
trigraphs[trigraph] = 1
while 1:
    c = f.read(1)
    if not c:
        break
    trigraph = trigraph[1:] + c
    if trigraph in trigraphs:
        trigraphs[trigraph] += 1
    else:
        trigraphs[trigraph] = 1





> See line 18, in the while loop.
>
> I was surprised that I could read in the whole billion file with one
> gulp without running out of memory.

Why? One billion bytes is less than a GB. It's a lot, but not *that* 
much.


> Memory usage went to 80% (from 
> the usual 35%), but no higher except at first, when I saw 98% for a
> few seconds, and then a drop to 78-80% where it stayed.

That suggests to me that your PC probably has 2GB of RAM. Am I close?



-- 
Steven D'Aprano

From davea at ieee.org  Sun Jul 18 11:45:33 2010
From: davea at ieee.org (Dave Angel)
Date: Sun, 18 Jul 2010 05:45:33 -0400
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTilC_X2q0sbXqzgC4JEUJLQST_Poq92SP8O8Vyy5@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com>
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com>
	<201007181101.33483.steve@pearwood.info>
	<AANLkTilC_X2q0sbXqzgC4JEUJLQST_Poq92SP8O8Vyy5@mail.gmail.com>
Message-ID: <4C42CD3D.7050804@ieee.org>

Richard D. Moores wrote:
> On Sat, Jul 17, 2010 at 18:01, Steven D'Aprano <steve at pearwood.info> wrote:
>   
>> <snip>
>>
>> import random
>> def random_digits(n):
>>    "Return n random digits with one call to random."
>>    return "%0*d" % (n, random.randrange(10**n))
>>
>>     
Thanks for implementing what I was suggesting, using zero-fill for 
getting a constant width string from a number.  No need for extra 
digits, or funny ranges
>> <snip>
> My <http://tutoree7.pastebin.com/9BMYZ08z> took 218 secs.
>
>   
>> Having generated the digits, it might be useful to look for deviations
>> from randomness. There should be approximately equal numbers of each
>> digit (100,000,000 each of 0, 1, 2, ..., 9), of each digraph
>> (10,000,000 each of 00, 01, 02, ..., 98, 99), trigraphs (1,000,000 each
>> of 000, ..., 999) and so forth.
>>     
>
> Yes. I'll do some checking. Thanks for the tips.
>   
>> The interesting question is, if you measure a deviation from the
>> equality (and you will), is it statistically significant? If so, it is
>> because of a problem with the random number generator, or with my
>> algorithm for generating the sample digits?
>>     
>
> Ah. Can't wait to see what turns up.
>
> Thanks, Steve.
>
> Dick
>
>   
If you care about the randomness, it's important to measure deviations 
from equal, and to make sure not only that they don't vary too much, but 
also that they don't vary too little.  If you measured exactly 100 
million 5's, you're very unlikely to have a real random string.

There are a series of tests you could perform, but I no longer have any 
references to what ones would be useful.  Years ago I inherited a random 
number generator in which the individual values seemed to be quite 
random, but adjacent pairs had some very definite patterns.  I ended up 
writing a new generator, from scratch, which was both much faster and 
much more random.  But I didn't do the testing myself.

DaveA


From rdmoores at gmail.com  Sun Jul 18 12:30:05 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sun, 18 Jul 2010 03:30:05 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <201007181926.08498.steve@pearwood.info>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<201007181101.33483.steve@pearwood.info>
	<AANLkTikWdpxwuwDPhY5mLOfvCBnHvLn-maxiK77RM5gv@mail.gmail.com> 
	<201007181926.08498.steve@pearwood.info>
Message-ID: <AANLkTinlCMfARi66TbSEME404UlzUWsUHLMUu3EhBjvD@mail.gmail.com>

On Sun, Jul 18, 2010 at 02:26, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sun, 18 Jul 2010 06:49:39 pm Richard D. Moores wrote:
>
>> I might try
>> trigraphs where the 2nd digit is 2 more than the first, and the third
>> 2 more than the 2nd. E.g. '024', '135', '791', '802'.
>
> Why the restriction? There's only 1000 different trigraphs (10*10*10),
> which is nothing.

Just to see if I could do it.  It seemed interesting.

>> Or maybe I've
>> had enough. BTW Steve, my script avoids the problem you mentioned, of
>> counting 2 '55's in a '555' string. I get only one, but 2 in '5555'.
>
> Huh? What problem did I mention?

Sorry, that was Luke.

> Taking the string '555', you should get two digraphs: 55_ and _55.

That seems wrong to me. When I search on '999999' and there's a
'9999999' I don't want to think I've found 2 instances of '999999'.
But that's just my preference.  Instances should be distinct, IMO, and
not overlap.

> In '5555' you should get three: 55__, _55_, __55. I'd do something like
> this (untested):
>
> trigraphs = {}
> f = open('digits')
> trigraph = f.read(3)  # read the first three digits
> trigraphs[trigraph] = 1
> while 1:
>    c = f.read(1)
>    if not c:
>        break
>    trigraph = trigraph[1:] + c
>    if trigraph in trigraphs:
>        trigraphs[trigraph] += 1
>    else:
>        trigraphs[trigraph] = 1
>> See line 18, in the while loop.
>>
>> I was surprised that I could read in the whole billion file with one
>> gulp without running out of memory.
>
> Why? One billion bytes is less than a GB. It's a lot, but not *that*
> much.

I earlier reported that my laptop couldn't handle even 800 million.

>> Memory usage went to 80% (from
>> the usual 35%), but no higher except at first, when I saw 98% for a
>> few seconds, and then a drop to 78-80% where it stayed.
>
> That suggests to me that your PC probably has 2GB of RAM. Am I close?

No. 4GB.

From steve at pearwood.info  Sun Jul 18 14:49:29 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 18 Jul 2010 22:49:29 +1000
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTinlCMfARi66TbSEME404UlzUWsUHLMUu3EhBjvD@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<201007181926.08498.steve@pearwood.info>
	<AANLkTinlCMfARi66TbSEME404UlzUWsUHLMUu3EhBjvD@mail.gmail.com>
Message-ID: <201007182249.30053.steve@pearwood.info>

On Sun, 18 Jul 2010 08:30:05 pm Richard D. Moores wrote:

> > Taking the string '555', you should get two digraphs: 55_ and _55.
>
> That seems wrong to me. When I search on '999999' and there's a
> '9999999' I don't want to think I've found 2 instances of '999999'.
> But that's just my preference.  Instances should be distinct, IMO,
> and not overlap.

I think we're talking about different things here. You're (apparently) 
interested in searching for patterns, in which case looking for 
non-overlapping patterns is perfectly fine. I'm talking about testing 
the randomness of the generator by counting the frequency of digraphs 
and trigraphs, in which case you absolutely do want them to overlap. 
Otherwise, you're throwing away every second digraph, or two out of 
every three trigraphs, which could potentially hide a lot of 
non-randomness.


> >> I was surprised that I could read in the whole billion file with
> >> one gulp without running out of memory.
> >
> > Why? One billion bytes is less than a GB. It's a lot, but not
> > *that* much.
>
> I earlier reported that my laptop couldn't handle even 800 million.

What do you mean, "couldn't handle"? Couldn't handle 800 million of 
what? Obviously not bytes, because your laptop *can* handle well over 
800 million bytes. It has 4GB of memory, after all :)

There's a big difference in memory usage between (say):

data = "1"*10**9  # a single string of one billion characters

and 

data = ["1"]*10**9  # a list of one billion separate strings

or even

number = 10**(1000000000)-1  # a one billion digit longint

This is just an example, of course. As they say, the devil is in the 
details.


> >> Memory usage went to 80% (from
> >> the usual 35%), but no higher except at first, when I saw 98% for
> >> a few seconds, and then a drop to 78-80% where it stayed.
> >
> > That suggests to me that your PC probably has 2GB of RAM. Am I
> > close?
>
> No. 4GB.

Interesting. Presumably the rest of the memory is being used by the 
operating system and other running applications and background 
processes.



-- 
Steven D'Aprano

From rdmoores at gmail.com  Sun Jul 18 15:22:15 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sun, 18 Jul 2010 06:22:15 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <201007182249.30053.steve@pearwood.info>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<201007181926.08498.steve@pearwood.info>
	<AANLkTinlCMfARi66TbSEME404UlzUWsUHLMUu3EhBjvD@mail.gmail.com> 
	<201007182249.30053.steve@pearwood.info>
Message-ID: <AANLkTikGKsEJt1MzjBh1u24atGmmueEMCXtfEPGNRdpu@mail.gmail.com>

On Sun, Jul 18, 2010 at 05:49, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sun, 18 Jul 2010 08:30:05 pm Richard D. Moores wrote:
>
>> > Taking the string '555', you should get two digraphs: 55_ and _55.
>>
>> That seems wrong to me. When I search on '999999' and there's a
>> '9999999' I don't want to think I've found 2 instances of '999999'.
>> But that's just my preference. ?Instances should be distinct, IMO,
>> and not overlap.
>
> I think we're talking about different things here.

Yes. I was as interested in finding non-overlapping patterns as
testing randomness, I suppose because we wouldn't have been sure about
the randomness anyway.

>You're (apparently)
> interested in searching for patterns, in which case looking for
> non-overlapping patterns is perfectly fine. I'm talking about testing
> the randomness of the generator by counting the frequency of digraphs
> and trigraphs, in which case you absolutely do want them to overlap.
> Otherwise, you're throwing away every second digraph, or two out of
> every three trigraphs, which could potentially hide a lot of
> non-randomness.
>
>
>> >> I was surprised that I could read in the whole billion file with
>> >> one gulp without running out of memory.
>> >
>> > Why? One billion bytes is less than a GB. It's a lot, but not
>> > *that* much.
>>
>> I earlier reported that my laptop couldn't handle even 800 million.
>
> What do you mean, "couldn't handle"? Couldn't handle 800 million of
> what? Obviously not bytes,

I meant what the context implied. Bytes. Look back in this thread to
see my description of my laptop's problems.

>because your laptop *can* handle well over
> 800 million bytes. It has 4GB of memory, after all :)
>
> There's a big difference in memory usage between (say):
>
> data = "1"*10**9 ?# a single string of one billion characters
>
> and
>
> data = ["1"]*10**9 ?# a list of one billion separate strings
>
> or even
>
> number = 10**(1000000000)-1 ?# a one billion digit longint
>
> This is just an example, of course. As they say, the devil is in the
> details.

Overkill, Steve.

>> >> Memory usage went to 80% (from
>> >> the usual 35%), but no higher except at first, when I saw 98% for
>> >> a few seconds, and then a drop to 78-80% where it stayed.
>> >
>> > That suggests to me that your PC probably has 2GB of RAM. Am I
>> > close?
>>
>> No. 4GB.
>
> Interesting. Presumably the rest of the memory is being used by the
> operating system and other running applications and background
> processes.

I suppose so.

Dick

From amartin7211 at gmail.com  Sun Jul 18 16:46:35 2010
From: amartin7211 at gmail.com (Andrew Martin)
Date: Sun, 18 Jul 2010 10:46:35 -0400
Subject: [Tutor] Return error message for my script in Blender
In-Reply-To: <201007181111.40566.steve@pearwood.info>
References: <AANLkTikpyQcYV7ZqP5hmVgb872r2F4RmHAo2DhXBI6vq@mail.gmail.com>
	<201007181111.40566.steve@pearwood.info>
Message-ID: <AANLkTileaNLn5QgC8JDUF5z7m7UMwtlzOUVKNa0X6Wd5@mail.gmail.com>

Yeah ok I get it. I have to return something.  I looked at the sample code
provided on the book's website and found out what I am supposed to return.
Thanks. I appreciate the responses, especially to this bonehead question.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100718/bb38e38c/attachment.html>

From amonroe at columbus.rr.com  Sun Jul 18 19:05:28 2010
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Sun, 18 Jul 2010 13:05:28 -0400
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
Message-ID: <119-1748710142.20100718130528@columbus.rr.com>

> That's the goal of the latest version of my script at
> <http://tutoree7.pastebin.com/5XYaaNfp>. The best I've been able to do
> so far is a file with 800 million digits.

I don't think anyone else has suggested this: the numpy module can
generate random bytes and has a built-in tofile() method.

Alan


From bgailer at gmail.com  Sun Jul 18 20:07:27 2010
From: bgailer at gmail.com (bob gailer)
Date: Sun, 18 Jul 2010 14:07:27 -0400
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <201007181101.33483.steve@pearwood.info>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com>	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com>
	<201007181101.33483.steve@pearwood.info>
Message-ID: <4C4342DF.6010404@gmail.com>

Check this out:

import random, time
s = time.time()
cycles = 1000
d = "0123456789"*100
f = open("numbers.txt", "w")
for i in xrange(n):
   l = []
   l.extend(random.sample(d, 1000))
   f.write(''.join(l))
f.close()
print time.time() - s

1 million in ~1.25 seconds

Therefore 1 billion in ~21 minutes. 3 ghz processor 2 g ram.

Changing length up or down seems to increase time.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From alan.gauld at btinternet.com  Mon Jul 19 01:11:04 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Jul 2010 00:11:04 +0100
Subject: [Tutor] A file containing a string of 1 billion random digits.
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<201007181926.08498.steve@pearwood.info><AANLkTinlCMfARi66TbSEME404UlzUWsUHLMUu3EhBjvD@mail.gmail.com>
	<201007182249.30053.steve@pearwood.info>
	<AANLkTikGKsEJt1MzjBh1u24atGmmueEMCXtfEPGNRdpu@mail.gmail.com>
Message-ID: <i201m8$4ki$1@dough.gmane.org>

"Richard D. Moores" <rdmoores at gmail.com> wrote

>>> I earlier reported that my laptop couldn't handle even 800 
>>> million.
>>
>> What do you mean, "couldn't handle"? Couldn't handle 800 million of
>> what? Obviously not bytes,
>
> I meant what the context implied. Bytes. Look back in this thread to
> see my description of my laptop's problems.

But you stored those in a list and then joined the list which meant 
you
actually at one point had two copies of the data, one in the list and
one in the string - that's >1.6billion bytes.

And these tests suuggest you only get about 2billion bytes of memory
to use which maybe explains why you were pushed to the limit at
800million.

HTH,

Alan G. 



From davea at ieee.org  Mon Jul 19 04:26:36 2010
From: davea at ieee.org (Dave Angel)
Date: Sun, 18 Jul 2010 22:26:36 -0400
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <201007182249.30053.steve@pearwood.info>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>	<201007181926.08498.steve@pearwood.info>	<AANLkTinlCMfARi66TbSEME404UlzUWsUHLMUu3EhBjvD@mail.gmail.com>
	<201007182249.30053.steve@pearwood.info>
Message-ID: <4C43B7DC.10505@ieee.org>

Steven D'Aprano wrote:
> On Sun, 18 Jul 2010 08:30:05 pm Richard D. Moores wrote:
>
>   
> <snip>
> What do you mean, "couldn't handle"? Couldn't handle 800 million of 
> what? Obviously not bytes, because your laptop *can* handle well over 
> 800 million bytes. It has 4GB of memory, after all :)
>
> <snip>

> This is just an example, of course. As they say, the devil is in the 
> details.
>
>
>   
>>>> Memory usage went to 80% (from
>>>> the usual 35%), but no higher except at first, when I saw 98% for
>>>> a few seconds, and then a drop to 78-80% where it stayed.
>>>>         
>>> That suggests to me that your PC probably has 2GB of RAM. Am I
>>> close?
>>>       
>> No. 4GB.
>>     
>
> Interesting. Presumably the rest of the memory is being used by the 
> operating system and other running applications and background 
> processes.
>
>
>   

The amount of physical RAM has little to do with the size that an 
application can reach.  An application is limited by several things, but 
physical RAM mostly has an effect on performance, not on the size of the 
app.

It is limited by the size of the swap file, and by how much of that swap 
file is in use by other apps, and by the system.  And a 32bit app is 
limited by the 4gb (virtual) address space, even if you have 8gb of 
physical RAM.  And that virtual space is shared with various pieces of 
OS, with device driver space, and sometimes with some physical hardware 
that's memory mapped.

But you can run a 2gb app in 1 gig of physical RAM.  That's what the 
swap file is for.

DaveA


From rdmoores at gmail.com  Mon Jul 19 09:50:27 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Mon, 19 Jul 2010 00:50:27 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <i201m8$4ki$1@dough.gmane.org>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<201007181926.08498.steve@pearwood.info>
	<AANLkTinlCMfARi66TbSEME404UlzUWsUHLMUu3EhBjvD@mail.gmail.com> 
	<201007182249.30053.steve@pearwood.info>
	<AANLkTikGKsEJt1MzjBh1u24atGmmueEMCXtfEPGNRdpu@mail.gmail.com> 
	<i201m8$4ki$1@dough.gmane.org>
Message-ID: <AANLkTinThT2HXdK1YfC7wH4RLRXUuUsFbP040TA9EVEP@mail.gmail.com>

On Sun, Jul 18, 2010 at 16:11, Alan Gauld <alan.gauld at btinternet.com> wrote:
> "Richard D. Moores" <rdmoores at gmail.com> wrote
>
>>>> I earlier reported that my laptop couldn't handle even 800 million.
>>>
>>> What do you mean, "couldn't handle"? Couldn't handle 800 million of
>>> what? Obviously not bytes,
>>
>> I meant what the context implied. Bytes. Look back in this thread to
>> see my description of my laptop's problems.
>
> But you stored those in a list and then joined the list which meant you
> actually at one point had two copies of the data, one in the list and
> one in the string - that's >1.6billion bytes.
>
> And these tests suggest you only get about 2billion bytes of memory
> to use which maybe explains why you were pushed to the limit at
> 800million.

Ah. Maybe it does. Thanks, Alan.

Following Dave Angel's info about the swap file, I took a look at my
64-bit Vista paging file size. The custom setting was 5944 MB. Without
really thinking that it would help, I changed the size to 8000 MB and
rebooted. I then tried my searching script
(<http://tutoree7.pastebin.com/rJ1naffZ>) on the 1 billion random
digits file, changing script lines 32 and 48 appropriately. As before,
this froze my laptop and I had to do an abrupt, forced shutdown. Don't
want to do too many of those.

Now, I don't really care about what a billion random digits might
contain. The first billion digits of pi, maybe -- but the most I have
so far is 100 million. If I can get gmpy to give me 900 million more,
then I'll try to figure out how to do your trick of getting one or two
small chunks at a time for searching. I do want to learn that stuff
(tell, seek, etc.), but I need to follow along in a good elementary
book first, I think.

Dick

From speederpython at gmail.com  Sun Jul 18 12:55:13 2010
From: speederpython at gmail.com (John Palmer)
Date: Sun, 18 Jul 2010 11:55:13 +0100
Subject: [Tutor] Help with Hangman program
Message-ID: <AANLkTikQGGlLOPUvSrb2uXRbt6sPKQqjCKzsEYyfzpJY@mail.gmail.com>

HI

This is my first attempt at writing my own program, (though I have been
through a couple of guides). For my first project I am doing a hangman game.
I have the program working nearly as I want it to be. The only problem is,
that when the user is prompted to enter its chosen word, (I am using a raw
input) and the word is typed in, it shows in the line above, which obviously
makes the game unplayable as the other person therefore can see the word in
front of them. Is there anyway making python hide this.

I have attached the project in a tar.gv as there is a picture which is used
aswell, I will also include the code below aswell (but if you copy and paste
then make sure you remove the image lines)

I am using python 2.6.5
and the os is Ubuntu 10.04

Thanks in advance for your help

Regards

John


The code is:

import Image

#User chooses the word

print
word = raw_input ("Choose your word ... ")


counter_total = 8 #Counter for the number of guesses

j = len(word) #Number of charactors in the word chosen
m = 0

star = "*" * j #Creates a string made up of * of the same number of
charactors as that of j

print star

letter_list = []
position = []

#Guessing the word

while (counter_total > 0) and (word != star):

    counter = 0 #a counter used to tell the user whether the letter was in
the word or not


#User guesses a letter
    print
    letter = raw_input("Choose a letter ... ")

#Checks to see if the letter chosen by the user is in the word

    for k in range(0,j):

        if letter == word[k]:
            letter_list.append(letter)
            position = []
            position.append(k)

            star = star[0:position[0]] + letter +star[position[0]+1:]
#ammend the star variable to include the correctly guessed letters in their
correct places

            print star

            counter = counter + 1

        else:
            counter = counter


#Tell the user if the letter was in the word or not
    if counter > 0 and star != word:
        print "Well done, guess again"
        m = len(letter_list)

    elif star == word:
        print

    else:
        print "Unlucky, guess again"
        counter_total = counter_total - 1
        print "You have %d guesses left" % (counter_total)


#If all letters are chosen then tell the user they are correct
if star == word:
    print "Congrats, you've won"
    print
    print "The word was " + word

#Tell the user if they've lost
if counter_total == 0:
    print "Game over!"
    print
    print "The word was " + word

#If user has lost, then show them picture
    im = Image.open("Hangman.jpg")
    im.show()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100718/c34cd7fc/attachment-0001.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Hangman Project.tar.gz
Type: application/x-gzip
Size: 54447 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100718/c34cd7fc/attachment-0001.bin>

From rdmoores at gmail.com  Mon Jul 19 11:17:48 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Mon, 19 Jul 2010 02:17:48 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <4C4342DF.6010404@gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com> 
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com> 
	<201007181101.33483.steve@pearwood.info> <4C4342DF.6010404@gmail.com>
Message-ID: <AANLkTimFilAk6VSxwaUb4ZP_XI_Qdxy7ItK9stldNQXC@mail.gmail.com>

On Sun, Jul 18, 2010 at 11:07, bob gailer <bgailer at gmail.com> wrote:

> Check this out:
>
> import random, time
> s = time.time()
> cycles = 1000
> d = "0123456789"*100
> f = open("numbers.txt", "w")
> for i in xrange(n):
>  l = []
>  l.extend(random.sample(d, 1000))
>  f.write(''.join(l))
> f.close()
> print time.time() - s
>
> 1 million in ~1.25 seconds
>
> Therefore 1 billion in ~21 minutes. 3 ghz processor 2 g ram.
>
> Changing length up or down seems to increase time.

Putting "cycles" where you have "n",  I used

import random, time
s = time.time()
cycles = 1000000
d = "0123456789"*100
f = open("/p31working/Data/1billion_digits_rand_num_Gailor.txt", "w")
for i in range(cycles):
    l = []
    l.extend(random.sample(d, 1000))
    f.write(''.join(l))
f.close()
print(time.time() - s)

to get 1 billion random digits into a file in 932 seconds (15.6
minutes).  <http://tutoree7.pastebin.com/Ldh6SX3q>, which uses Steve
D'Aprano's random_digits function, took 201 seconds (3.35 minutes).

Still, I understand yours, and not his (the return line). I'd never
noticed random.sample() before, nor tried out extend() on a list.  So
thanks, Bob.

Dick

From alan.gauld at btinternet.com  Mon Jul 19 11:20:58 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Jul 2010 10:20:58 +0100
Subject: [Tutor] Help with Hangman program
References: <AANLkTikQGGlLOPUvSrb2uXRbt6sPKQqjCKzsEYyfzpJY@mail.gmail.com>
Message-ID: <i215dm$miv$1@dough.gmane.org>


"John Palmer" <speederpython at gmail.com> wrote

> I have the program working nearly as I want it to be. The only 
> problem is,
> that when the user is prompted to enter its chosen word, (I am using 
> a raw
> input) and the word is typed in, it shows in the line above,

Take a look at the getpass module.

HTH,


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



From alan.gauld at btinternet.com  Mon Jul 19 12:59:05 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Jul 2010 11:59:05 +0100
Subject: [Tutor] A file containing a string of 1 billion random digits.
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com>
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com>
	<201007181101.33483.steve@pearwood.info>
	<4C4342DF.6010404@gmail.com>
	<AANLkTimFilAk6VSxwaUb4ZP_XI_Qdxy7ItK9stldNQXC@mail.gmail.com>
Message-ID: <i21b5p$9ia$1@dough.gmane.org>

"Richard D. Moores" <rdmoores at gmail.com> wrote 

> Still, I understand yours, and not his (the return line). 

return "%0*d" % (n, random.randrange(10**n))

"%0*d"

The asterisk is quite unusual but basically means 
substitute the next argument but treat it as part of 
the format string. So:

>>> "%0*d" % (2,8)   # becomes same as "%02d"
'08'
>>> "%0*d" % (7,8)   # becomes same as "%07d"
'0000008'

So for the return statement with n = 4 it would give 

"%04d" % x

where x is a random number from range(10000).
That becomes

0dddd

where dddd is the random number


The same thing can be done in two steps with:

fmt = "%0%dd" % n   # eg. gives "%04d"  if n is 4
return fmt % randrange(....)

But the asterisk is neater (and faster) but can become hard to 
read, and debug, if over-used - like if there are many arguments 
in a single string!

HTH,

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



From rdmoores at gmail.com  Mon Jul 19 13:28:49 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Mon, 19 Jul 2010 04:28:49 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <i21b5p$9ia$1@dough.gmane.org>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com> 
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com> 
	<201007181101.33483.steve@pearwood.info> <4C4342DF.6010404@gmail.com> 
	<AANLkTimFilAk6VSxwaUb4ZP_XI_Qdxy7ItK9stldNQXC@mail.gmail.com> 
	<i21b5p$9ia$1@dough.gmane.org>
Message-ID: <AANLkTikR6Q6sQYvrdUb4F1iAfnoMwTtLFGCs978fG6oF@mail.gmail.com>

On Mon, Jul 19, 2010 at 03:59, Alan Gauld <alan.gauld at btinternet.com> wrote:
> "Richard D. Moores" <rdmoores at gmail.com> wrote
>>
>> Still, I understand yours, and not his (the return line).
>
> return "%0*d" % (n, random.randrange(10**n))
>
> "%0*d"
>
> The asterisk is quite unusual but basically means substitute the next
> argument but treat it as part of the format string. So:
>
>>>> "%0*d" % (2,8) ? # becomes same as "%02d"
>
> '08'
>>>>
>>>> "%0*d" % (7,8) ? # becomes same as "%07d"
>
> '0000008'
>
> So for the return statement with n = 4 it would give
> "%04d" % x
>
> where x is a random number from range(10000).
> That becomes
>
> 0dddd
>
> where dddd is the random number

Just tried it with 4 and executed many times. Seems the 0 in 0dddd is
there when a dddd is a 3-digit number such as 123. In that case a zero
is prefixed to 123 to produce 0123. Or if just 23, 2 zeros are
prefixed, etc. Correct?

>
>
> The same thing can be done in two steps with:
>
> fmt = "%0%dd" % n ? # eg. gives "%04d" ?if n is 4
> return fmt % randrange(....)
>
> But the asterisk is neater (and faster) but can become hard to read, and
> debug, if over-used - like if there are many arguments in a single string!
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From speederpython at gmail.com  Mon Jul 19 13:37:25 2010
From: speederpython at gmail.com (John Palmer)
Date: Mon, 19 Jul 2010 12:37:25 +0100
Subject: [Tutor] Contents of Tutor digest, help with Hangman program
Message-ID: <AANLkTinfQmnIJxwiQfAMYgVSwNnNqtblgcA7GW7h42vF@mail.gmail.com>

Hi Alan thanks for the help. I did try the getpass module, I think I used:

getpass.getpass()

This actually prompted the user to enter a password, which isn't really what
I want. Unless there's something i'm missing with this module? I'll take
another look anyway.




On 19 July 2010 11:00, <tutor-request at python.org> wrote:

> Send Tutor mailing list submissions to
>        tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>        http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>        tutor-request at python.org
>
> You can reach the person managing the list at
>        tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>   1. Re: A file containing a string of 1 billion random digits.
>      (Richard D. Moores)
>   2. Re: Help with Hangman program (Alan Gauld)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Mon, 19 Jul 2010 02:17:48 -0700
> From: "Richard D. Moores" <rdmoores at gmail.com>
> To: bob gailer <bgailer at gmail.com>
> Cc: tutor at python.org
> Subject: Re: [Tutor] A file containing a string of 1 billion random
>        digits.
> Message-ID:
>        <AANLkTimFilAk6VSxwaUb4ZP_XI_Qdxy7ItK9stldNQXC at mail.gmail.com>
> Content-Type: text/plain; charset=UTF-8
>
> On Sun, Jul 18, 2010 at 11:07, bob gailer <bgailer at gmail.com> wrote:
>
> > Check this out:
> >
> > import random, time
> > s = time.time()
> > cycles = 1000
> > d = "0123456789"*100
> > f = open("numbers.txt", "w")
> > for i in xrange(n):
> >  l = []
> >  l.extend(random.sample(d, 1000))
> >  f.write(''.join(l))
> > f.close()
> > print time.time() - s
> >
> > 1 million in ~1.25 seconds
> >
> > Therefore 1 billion in ~21 minutes. 3 ghz processor 2 g ram.
> >
> > Changing length up or down seems to increase time.
>
> Putting "cycles" where you have "n",  I used
>
> import random, time
> s = time.time()
> cycles = 1000000
> d = "0123456789"*100
> f = open("/p31working/Data/1billion_digits_rand_num_Gailor.txt", "w")
> for i in range(cycles):
>    l = []
>    l.extend(random.sample(d, 1000))
>    f.write(''.join(l))
> f.close()
> print(time.time() - s)
>
> to get 1 billion random digits into a file in 932 seconds (15.6
> minutes).  <http://tutoree7.pastebin.com/Ldh6SX3q>, which uses Steve
> D'Aprano's random_digits function, took 201 seconds (3.35 minutes).
>
> Still, I understand yours, and not his (the return line). I'd never
> noticed random.sample() before, nor tried out extend() on a list.  So
> thanks, Bob.
>
> Dick
>
>
> ------------------------------
>
> Message: 2
> Date: Mon, 19 Jul 2010 10:20:58 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> To: tutor at python.org
> Subject: Re: [Tutor] Help with Hangman program
> Message-ID: <i215dm$miv$1 at dough.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>        reply-type=original
>
>
> "John Palmer" <speederpython at gmail.com> wrote
>
> > I have the program working nearly as I want it to be. The only
> > problem is,
> > that when the user is prompted to enter its chosen word, (I am using
> > a raw
> > input) and the word is typed in, it shows in the line above,
>
> Take a look at the getpass module.
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 77, Issue 68
> *************************************
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100719/ff9baab2/attachment.html>

From __peter__ at web.de  Mon Jul 19 13:51:06 2010
From: __peter__ at web.de (Peter Otten)
Date: Mon, 19 Jul 2010 13:51:06 +0200
Subject: [Tutor] A file containing a string of 1 billion random digits.
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com>
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com>
	<201007181101.33483.steve@pearwood.info>
	<4C4342DF.6010404@gmail.com>
Message-ID: <i21e74$jur$1@dough.gmane.org>

bob gailer wrote:

> Check this out:
> 
> import random, time
> s = time.time()
> cycles = 1000
> d = "0123456789"*100
> f = open("numbers.txt", "w")
> for i in xrange(n):
>    l = []
>    l.extend(random.sample(d, 1000))
>    f.write(''.join(l))
> f.close()
> print time.time() - s

Note that this is not random. E. g. the start sequence "0"*101 should have a 
likelyhood of 1/10**101 but is impossible to generate with your setup.

Peter


From rdmoores at gmail.com  Mon Jul 19 14:29:53 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Mon, 19 Jul 2010 05:29:53 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTikJqpLFIZ5GHvLcRQgxZi8nqLXFBOH7m5tR4LmG@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com> 
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com> 
	<201007181101.33483.steve@pearwood.info> <4C4342DF.6010404@gmail.com> 
	<i21e74$jur$1@dough.gmane.org>
	<AANLkTikJqpLFIZ5GHvLcRQgxZi8nqLXFBOH7m5tR4LmG@mail.gmail.com>
Message-ID: <AANLkTilMVsJ-wlyEYdSauBHcIjz1yjgiom8I6B6QQFvh@mail.gmail.com>

On Mon, Jul 19, 2010 at 04:51, Peter Otten <__peter__ at web.de> wrote:
> bob gailer wrote:
>
>> Check this out:
>>
>> import random, time
>> s = time.time()
>> cycles = 1000
>> d = "0123456789"*100
>> f = open("numbers.txt", "w")
>> for i in xrange(n):
>> ? ?l = []
>> ? ?l.extend(random.sample(d, 1000))
>> ? ?f.write(''.join(l))
>> f.close()
>> print time.time() - s
>
> Note that this is not random. E. g. the start sequence "0"*101 should have a
> likelyhood of 1/10**101 but is impossible to generate with your setup.
I not sure exactly what you mean, because I don't fully understand
that '*' (despite Alan's patient explanation), but if you run

import random
cycles = 100000
d = "0123456789"*10
for i in range(cycles):
? ?l = []
? ?l.extend(random.sample(d, 100))
? ?s = (''.join(l))
? ?if s[:4] == '0101':
? ? ? ?print(s)

You'll see a bunch of strings that begin with "0101"

Or if you run

import random
cycles = 50
d = "0123456789"*10
for i in range(cycles):
? ?l = []
? ?l.extend(random.sample(d, 100))
? ?s = (''.join(l))
? ?if s[:1] == '0':
? ? ? ?print(s)

You'll see some that begin with '0'.

Am I on the right track?

Dick

From __peter__ at web.de  Mon Jul 19 15:45:43 2010
From: __peter__ at web.de (Peter Otten)
Date: Mon, 19 Jul 2010 15:45:43 +0200
Subject: [Tutor] A file containing a string of 1 billion random digits.
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com>
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com>
	<201007181101.33483.steve@pearwood.info>
	<4C4342DF.6010404@gmail.com> <i21e74$jur$1@dough.gmane.org>
	<AANLkTikJqpLFIZ5GHvLcRQgxZi8nqLXFBOH7m5tR4LmG@mail.gmail.com>
	<AANLkTilMVsJ-wlyEYdSauBHcIjz1yjgiom8I6B6QQFvh@mail.gmail.com>
Message-ID: <i21ku0$e00$1@dough.gmane.org>

Richard D. Moores wrote:

> On Mon, Jul 19, 2010 at 04:51, Peter Otten <__peter__ at web.de> wrote:
>> bob gailer wrote:
>>
>>> Check this out:
>>>
>>> import random, time
>>> s = time.time()
>>> cycles = 1000
>>> d = "0123456789"*100
>>> f = open("numbers.txt", "w")
>>> for i in xrange(n):
>>> l = []
>>> l.extend(random.sample(d, 1000))
>>> f.write(''.join(l))
>>> f.close()
>>> print time.time() - s
>>
>> Note that this is not random. E. g. the start sequence "0"*101 should
>> have a likelyhood of 1/10**101 but is impossible to generate with your
>> setup.
> I not sure exactly what you mean, because I don't fully understand
> that '*' (despite Alan's patient explanation), but if you run
> 
> import random
> cycles = 100000
> d = "0123456789"*10
> for i in range(cycles):
> l = []
> l.extend(random.sample(d, 100))
> s = (''.join(l))
> if s[:4] == '0101':
> print(s)
> 
> You'll see a bunch of strings that begin with "0101"
> 
> Or if you run
> 
> import random
> cycles = 50
> d = "0123456789"*10
> for i in range(cycles):
> l = []
> l.extend(random.sample(d, 100))
> s = (''.join(l))
> if s[:1] == '0':
> print(s)
> 
> You'll see some that begin with '0'.
> 
> Am I on the right track?

No. If you fire up your python interpreter you can do

>>> "0"*10
'0000000000'

i. e. "0"*101 is a sequence of 101 zeros. Because a sample can pick every 
item in the population only once and there are only 100 zeros, at most 100 
of them can be drawn, and the more are drawn the less likely it becomes that 
another one is drawn. The simplest demo is probably

random.sample([0, 1], 2)

Possible returns are [0, 1] and [1, 0], but for true randomness you want [1, 
1] and [0, 0], too. The more often the items are repeated the less 
pronounced that bias becomes, e. g.

random.sample([0, 1, 0, 1], 2)

can produce all combinations, but [0, 1] is twice as likely as [0, 0] 
because once the first 0 is drawn there is only one 0 left, but two 1s.
Here's a demonstration:

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i in range(1000):
...     d[tuple(random.sample([0, 1]*2, 2))] += 1
...
>>> dict(d)
{(0, 1): 333, (1, 0): 308, (0, 0): 174, (1, 1): 185}

Peter


From alan.gauld at btinternet.com  Mon Jul 19 16:14:18 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Mon, 19 Jul 2010 07:14:18 -0700 (PDT)
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTikR6Q6sQYvrdUb4F1iAfnoMwTtLFGCs978fG6oF@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com>
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com>
	<201007181101.33483.steve@pearwood.info>
	<4C4342DF.6010404@gmail.com>
	<AANLkTimFilAk6VSxwaUb4ZP_XI_Qdxy7ItK9stldNQXC@mail.gmail.com>
	<i21b5p$9ia$1@dough.gmane.org>
	<AANLkTikR6Q6sQYvrdUb4F1iAfnoMwTtLFGCs978fG6oF@mail.gmail.com>
Message-ID: <94846.12586.qm@web86706.mail.ird.yahoo.com>



> 4 and executed many times. Seems the 0 in 0dddd is
> there when a dddd is a 3-digit number such as 123. 
> In that case a zero is prefixed to 123 to produce 
> 0123. Or if just 23, 2 zeros are prefixed, etc. 
> Correct?

Yes, the zero indicates that the string should be padded
with zeros to the length specified. The format string 
documentation gives all the details but while zero 
padding is fairly common the asterisk is less so, that's 
why I explained it but not the zero...I assumed it was 
the asterisk that was confusing you...

HTH,

Alan G.


From rdmoores at gmail.com  Mon Jul 19 16:14:13 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Mon, 19 Jul 2010 07:14:13 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <i21ku0$e00$1@dough.gmane.org>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com> 
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com> 
	<201007181101.33483.steve@pearwood.info> <4C4342DF.6010404@gmail.com> 
	<i21e74$jur$1@dough.gmane.org>
	<AANLkTikJqpLFIZ5GHvLcRQgxZi8nqLXFBOH7m5tR4LmG@mail.gmail.com> 
	<AANLkTilMVsJ-wlyEYdSauBHcIjz1yjgiom8I6B6QQFvh@mail.gmail.com> 
	<i21ku0$e00$1@dough.gmane.org>
Message-ID: <AANLkTikctB03vyzHhhvmpg8Hrf6lMhRDIGbtKcoNPcn-@mail.gmail.com>

On Mon, Jul 19, 2010 at 06:45, Peter Otten <__peter__ at web.de> wrote:

> No. If you fire up your python interpreter you can do
>
>>>> "0"*10
> '0000000000'

Ah, you're absolutely right. Sorry, I misunderstood you and your '*'.
Good catch.

Dick

From rdmoores at gmail.com  Mon Jul 19 16:48:13 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Mon, 19 Jul 2010 07:48:13 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <94846.12586.qm@web86706.mail.ird.yahoo.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com> 
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com> 
	<201007181101.33483.steve@pearwood.info> <4C4342DF.6010404@gmail.com> 
	<AANLkTimFilAk6VSxwaUb4ZP_XI_Qdxy7ItK9stldNQXC@mail.gmail.com> 
	<i21b5p$9ia$1@dough.gmane.org>
	<AANLkTikR6Q6sQYvrdUb4F1iAfnoMwTtLFGCs978fG6oF@mail.gmail.com> 
	<94846.12586.qm@web86706.mail.ird.yahoo.com>
Message-ID: <AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_@mail.gmail.com>

On Mon, Jul 19, 2010 at 07:14, ALAN GAULD <alan.gauld at btinternet.com> wrote:
>
>
>> 4 and executed many times. Seems the 0 in 0dddd is
>> there when a dddd is a 3-digit number such as 123.
>> In that case a zero is prefixed to 123 to produce
>> 0123. Or if just 23, 2 zeros are prefixed, etc.
>> Correct?
>
> Yes, the zero indicates that the string should be padded
> with zeros to the length specified. The format string
> documentation gives all the details

I've been unable to find any mention of that use of the asterisk in
the 3.1 docs, in

http://docs.python.org/py3k/library/string.html#formatspec

or

http://docs.python.org/py3k/library/string.html#formatstrings

Suggestion?

Dick

From steve at pearwood.info  Mon Jul 19 16:54:57 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 20 Jul 2010 00:54:57 +1000
Subject: [Tutor] Contents of Tutor digest, help with Hangman program
In-Reply-To: <AANLkTinfQmnIJxwiQfAMYgVSwNnNqtblgcA7GW7h42vF@mail.gmail.com>
References: <AANLkTinfQmnIJxwiQfAMYgVSwNnNqtblgcA7GW7h42vF@mail.gmail.com>
Message-ID: <201007200054.57927.steve@pearwood.info>

On Mon, 19 Jul 2010 09:37:25 pm John Palmer wrote:
> Hi Alan thanks for the help. I did try the getpass module, I think I
> used:
>
> getpass.getpass()
>
> This actually prompted the user to enter a password, which isn't
> really what I want. Unless there's something i'm missing with this
> module? I'll take another look anyway.

Tell the function what prompt to use:

>>> import getpass
>>> s = getpass.getpass("Please enter your secret word: ")
Please enter your secret word:
>>> 
>>> print s
anti-disestablishmentarianism



-- 
Steven D'Aprano

From bgailer at gmail.com  Mon Jul 19 16:57:11 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 19 Jul 2010 10:57:11 -0400
Subject: [Tutor] Contents of Tutor digest, help with Hangman program
In-Reply-To: <AANLkTinfQmnIJxwiQfAMYgVSwNnNqtblgcA7GW7h42vF@mail.gmail.com>
References: <AANLkTinfQmnIJxwiQfAMYgVSwNnNqtblgcA7GW7h42vF@mail.gmail.com>
Message-ID: <4C4467C7.1060701@gmail.com>

On 7/19/2010 7:37 AM, John Palmer wrote:
> Hi Alan thanks for the help. I did try the getpass module, I think I 
> used:
>
> getpass.getpass()
>
> This actually prompted the user to enter a password, which isn't 
> really what I want. Unless there's something i'm missing with this 
> module? I'll take another look anyway.

Reading the documentation (15.7 in Python 3):

The getpass module provides two functions:

getpass.getpass(/prompt='Password: '/, /stream=None/)? 
<http://docs.python.org/py3k/library/getpass.html?highlight=getpass#getpass.getpass>

    Prompt the user for a password without echoing. The user is prompted
    using the string /prompt/, which defaults to 'Password: '.

HTH

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100719/20256873/attachment.html>

From steve at pearwood.info  Mon Jul 19 17:01:58 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 20 Jul 2010 01:01:58 +1000
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<94846.12586.qm@web86706.mail.ird.yahoo.com>
	<AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_@mail.gmail.com>
Message-ID: <201007200101.58268.steve@pearwood.info>

On Tue, 20 Jul 2010 12:48:13 am Richard D. Moores wrote:
> On Mon, Jul 19, 2010 at 07:14, ALAN GAULD <alan.gauld at btinternet.com> 
wrote:
> >> 4 and executed many times. Seems the 0 in 0dddd is
> >> there when a dddd is a 3-digit number such as 123.
> >> In that case a zero is prefixed to 123 to produce
> >> 0123. Or if just 23, 2 zeros are prefixed, etc.
> >> Correct?
> >
> > Yes, the zero indicates that the string should be padded
> > with zeros to the length specified. The format string
> > documentation gives all the details
>
> I've been unable to find any mention of that use of the asterisk in
> the 3.1 docs, in
>
> http://docs.python.org/py3k/library/string.html#formatspec
>
> or
>
> http://docs.python.org/py3k/library/string.html#formatstrings
>
> Suggestion?

You're looking in the wrong place. This is not part of format strings, 
as it doesn't use the str.format() method. It uses the % string 
interpolation operator.

http://docs.python.org/py3k/library/stdtypes.html#old-string-formatting-operations


You can get the same result with the format mini-language. See the 
example "Nested arguments and more complex examples" just before the 
section on Template Strings here:

http://docs.python.org/py3k/library/string.html#format-specification-mini-language




-- 
Steven D'Aprano

From bgailer at gmail.com  Mon Jul 19 17:06:15 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 19 Jul 2010 11:06:15 -0400
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com>
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com>
	<201007181101.33483.steve@pearwood.info>
	<4C4342DF.6010404@gmail.com>
	<AANLkTimFilAk6VSxwaUb4ZP_XI_Qdxy7ItK9stldNQXC@mail.gmail.com>
	<i21b5p$9ia$1@dough.gmane.org>	<AANLkTikR6Q6sQYvrdUb4F1iAfnoMwTtLFGCs978fG6oF@mail.gmail.com>
	<94846.12586.qm@web86706.mail.ird.yahoo.com>
	<AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_@mail.gmail.com>
Message-ID: <4C4469E7.6050404@gmail.com>

On 7/19/2010 10:48 AM, Richard D. Moores wrote:
>
> I've been unable to find any mention of that use of the asterisk in
> the 3.1 docs
>    

http://docs.python.org/py3k/library/stdtypes.html#old-string-formatting


-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From bgailer at gmail.com  Mon Jul 19 17:10:06 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 19 Jul 2010 11:10:06 -0400
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <i21ku0$e00$1@dough.gmane.org>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com>	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com>	<201007181101.33483.steve@pearwood.info>	<4C4342DF.6010404@gmail.com>
	<i21e74$jur$1@dough.gmane.org>	<AANLkTikJqpLFIZ5GHvLcRQgxZi8nqLXFBOH7m5tR4LmG@mail.gmail.com>	<AANLkTilMVsJ-wlyEYdSauBHcIjz1yjgiom8I6B6QQFvh@mail.gmail.com>
	<i21ku0$e00$1@dough.gmane.org>
Message-ID: <4C446ACE.1010207@gmail.com>

[snip]

I did not read the documentation with enough understanding. I withdraw the use of sample.


Sigh!

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From rdmoores at gmail.com  Mon Jul 19 17:42:51 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Mon, 19 Jul 2010 08:42:51 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <201007200101.58268.steve@pearwood.info>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<94846.12586.qm@web86706.mail.ird.yahoo.com>
	<AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_@mail.gmail.com> 
	<201007200101.58268.steve@pearwood.info>
Message-ID: <AANLkTineoXcQ59R03sXpoxNyGYsSIASRq_s80DgwOPmf@mail.gmail.com>

On Mon, Jul 19, 2010 at 08:01, Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, 20 Jul 2010 12:48:13 am Richard D. Moores wrote:

> You're looking in the wrong place. This is not part of format strings,
> as it doesn't use the str.format() method. It uses the % string
> interpolation operator.
>
> http://docs.python.org/py3k/library/stdtypes.html#old-string-formatting-operations

Yes. I now see the asterisk use in 4. But also:

Note

The formatting operations described here are obsolete and may go away
in future versions of Python. Use the new String Formatting in new
code.

I hope that use of '*' does disappear. It's the most confusing thing
I've recently tried to get my mind around! Before that, maybe, was the
Trinity..

> You can get the same result with the format mini-language. See the
> example "Nested arguments and more complex examples" just before the
> section on Template Strings here:
>
> http://docs.python.org/py3k/library/string.html#format-specification-mini-language

OK, I'll try to sink my teeth into this. I just found that Learning
Python, 4th ed. has a discussion of all of this beginning at p.181 in
the book, or p.233 in the PDF.

Thanks, Steve.

Dick

From bala.biophysics at gmail.com  Mon Jul 19 18:18:54 2010
From: bala.biophysics at gmail.com (Bala subramanian)
Date: Mon, 19 Jul 2010 18:18:54 +0200
Subject: [Tutor] searching for multiple strings in line.starswith()
Message-ID: <AANLkTimbFhhTie0PoOWUuZC2cXJEErr8j3gF1m3m1cTS@mail.gmail.com>

Friends,
I have to extract the line from a file that does not contain a set of
strings in the start of the line, i wrote the following code.

for index, line in enumerate(myvar.split('\n')):
    if line.startswith('') not in ['#Cluster','#Centroid','#End']:
        line=line.split()
        print line

The code works without error but it seems that the condition is not applied.
What is the correct way of searching for multiple strings at the start of a
line.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100719/d0139dba/attachment.html>

From speederpython at gmail.com  Mon Jul 19 18:20:35 2010
From: speederpython at gmail.com (John Palmer)
Date: Mon, 19 Jul 2010 17:20:35 +0100
Subject: [Tutor] Contents of Tutor digest, Help with hangman
Message-ID: <AANLkTikK9uhSyztcNoLWWs-C_RgiUa6qc1P1XD3__P6b@mail.gmail.com>

Thanks a lot for the help guys, but when I use the getpass.getpass(Enter
your word here, I get a different response to what you get. This is what
happen with mine:

>>> import getpass
>>> s = getpass.getpass("Enter your word here: ")
Warning: Password input may be echoed.
Please enter your secret word: hangman

>>> s
'hangman'
>>>


I'm guessing that its something to do with the "Warning: Password may be
echoed" line. In the documentation it says:

"If echo free input is unavailable getpass() falls back to printing a
warning message to stream and reading
from sys.stdin and issuing a GetPassWarning."

But i'm not sure what that means, sry to be a pain, and again thanks for all
the help.

I did manage to find another solution which is just to print a large number
of blank lines, which just moved the line with the word in it off the
screen, but I don't really like it to be honest. The getpass module seems to
be the best solution i just don't understand why its not working for me.

Regards
John



On 19 July 2010 16:02, <tutor-request at python.org> wrote:

> Send Tutor mailing list submissions to
>        tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>        http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>        tutor-request at python.org
>
> You can reach the person managing the list at
>        tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>   1. Re: A file containing a string of 1 billion random digits.
>      (Peter Otten)
>   2. Re: A file containing a string of 1 billion random digits.
>      (ALAN GAULD)
>   3. Re: A file containing a string of 1 billion random digits.
>      (Richard D. Moores)
>   4. Re: A file containing a string of 1 billion random digits.
>      (Richard D. Moores)
>   5. Re: Contents of Tutor digest, help with Hangman program
>      (Steven D'Aprano)
>   6. Re: Contents of Tutor digest, help with Hangman program
>      (bob gailer)
>   7. Re: A file containing a string of 1 billion random digits.
>      (Steven D'Aprano)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Mon, 19 Jul 2010 15:45:43 +0200
> From: Peter Otten <__peter__ at web.de>
> To: tutor at python.org
> Subject: Re: [Tutor] A file containing a string of 1 billion random
>        digits.
> Message-ID: <i21ku0$e00$1 at dough.gmane.org>
> Content-Type: text/plain; charset="ISO-8859-1"
>
> Richard D. Moores wrote:
>
> > On Mon, Jul 19, 2010 at 04:51, Peter Otten <__peter__ at web.de> wrote:
> >> bob gailer wrote:
> >>
> >>> Check this out:
> >>>
> >>> import random, time
> >>> s = time.time()
> >>> cycles = 1000
> >>> d = "0123456789"*100
> >>> f = open("numbers.txt", "w")
> >>> for i in xrange(n):
> >>> l = []
> >>> l.extend(random.sample(d, 1000))
> >>> f.write(''.join(l))
> >>> f.close()
> >>> print time.time() - s
> >>
> >> Note that this is not random. E. g. the start sequence "0"*101 should
> >> have a likelyhood of 1/10**101 but is impossible to generate with your
> >> setup.
> > I not sure exactly what you mean, because I don't fully understand
> > that '*' (despite Alan's patient explanation), but if you run
> >
> > import random
> > cycles = 100000
> > d = "0123456789"*10
> > for i in range(cycles):
> > l = []
> > l.extend(random.sample(d, 100))
> > s = (''.join(l))
> > if s[:4] == '0101':
> > print(s)
> >
> > You'll see a bunch of strings that begin with "0101"
> >
> > Or if you run
> >
> > import random
> > cycles = 50
> > d = "0123456789"*10
> > for i in range(cycles):
> > l = []
> > l.extend(random.sample(d, 100))
> > s = (''.join(l))
> > if s[:1] == '0':
> > print(s)
> >
> > You'll see some that begin with '0'.
> >
> > Am I on the right track?
>
> No. If you fire up your python interpreter you can do
>
> >>> "0"*10
> '0000000000'
>
> i. e. "0"*101 is a sequence of 101 zeros. Because a sample can pick every
> item in the population only once and there are only 100 zeros, at most 100
> of them can be drawn, and the more are drawn the less likely it becomes
> that
> another one is drawn. The simplest demo is probably
>
> random.sample([0, 1], 2)
>
> Possible returns are [0, 1] and [1, 0], but for true randomness you want
> [1,
> 1] and [0, 0], too. The more often the items are repeated the less
> pronounced that bias becomes, e. g.
>
> random.sample([0, 1, 0, 1], 2)
>
> can produce all combinations, but [0, 1] is twice as likely as [0, 0]
> because once the first 0 is drawn there is only one 0 left, but two 1s.
> Here's a demonstration:
>
> >>> from collections import defaultdict
> >>> d = defaultdict(int)
> >>> for i in range(1000):
> ...     d[tuple(random.sample([0, 1]*2, 2))] += 1
> ...
> >>> dict(d)
> {(0, 1): 333, (1, 0): 308, (0, 0): 174, (1, 1): 185}
>
> Peter
>
>
>
> ------------------------------
>
> Message: 2
> Date: Mon, 19 Jul 2010 07:14:18 -0700 (PDT)
> From: ALAN GAULD <alan.gauld at btinternet.com>
> To: "Richard D. Moores" <rdmoores at gmail.com>
> Cc: tutor at python.org
> Subject: Re: [Tutor] A file containing a string of 1 billion random
>        digits.
> Message-ID: <94846.12586.qm at web86706.mail.ird.yahoo.com>
> Content-Type: text/plain; charset=utf-8
>
>
>
> > 4 and executed many times. Seems the 0 in 0dddd is
> > there when a dddd is a 3-digit number such as 123.
> > In that case a zero is prefixed to 123 to produce
> > 0123. Or if just 23, 2 zeros are prefixed, etc.
> > Correct?
>
> Yes, the zero indicates that the string should be padded
> with zeros to the length specified. The format string
> documentation gives all the details but while zero
> padding is fairly common the asterisk is less so, that's
> why I explained it but not the zero...I assumed it was
> the asterisk that was confusing you...
>
> HTH,
>
> Alan G.
>
>
>
> ------------------------------
>
> Message: 3
> Date: Mon, 19 Jul 2010 07:14:13 -0700
> From: "Richard D. Moores" <rdmoores at gmail.com>
> To: Peter Otten <__peter__ at web.de>
> Cc: tutor at python.org
> Subject: Re: [Tutor] A file containing a string of 1 billion random
>        digits.
> Message-ID:
>        <AANLkTikctB03vyzHhhvmpg8Hrf6lMhRDIGbtKcoNPcn- at mail.gmail.com>
> Content-Type: text/plain; charset=UTF-8
>
> On Mon, Jul 19, 2010 at 06:45, Peter Otten <__peter__ at web.de> wrote:
>
> > No. If you fire up your python interpreter you can do
> >
> >>>> "0"*10
> > '0000000000'
>
> Ah, you're absolutely right. Sorry, I misunderstood you and your '*'.
> Good catch.
>
> Dick
>
>
> ------------------------------
>
> Message: 4
> Date: Mon, 19 Jul 2010 07:48:13 -0700
> From: "Richard D. Moores" <rdmoores at gmail.com>
> To: ALAN GAULD <alan.gauld at btinternet.com>
> Cc: tutor at python.org
> Subject: Re: [Tutor] A file containing a string of 1 billion random
>        digits.
> Message-ID:
>        <AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_ at mail.gmail.com>
> Content-Type: text/plain; charset=UTF-8
>
> On Mon, Jul 19, 2010 at 07:14, ALAN GAULD <alan.gauld at btinternet.com>
> wrote:
> >
> >
> >> 4 and executed many times. Seems the 0 in 0dddd is
> >> there when a dddd is a 3-digit number such as 123.
> >> In that case a zero is prefixed to 123 to produce
> >> 0123. Or if just 23, 2 zeros are prefixed, etc.
> >> Correct?
> >
> > Yes, the zero indicates that the string should be padded
> > with zeros to the length specified. The format string
> > documentation gives all the details
>
> I've been unable to find any mention of that use of the asterisk in
> the 3.1 docs, in
>
> http://docs.python.org/py3k/library/string.html#formatspec
>
> or
>
> http://docs.python.org/py3k/library/string.html#formatstrings
>
> Suggestion?
>
> Dick
>
>
> ------------------------------
>
> Message: 5
> Date: Tue, 20 Jul 2010 00:54:57 +1000
> From: Steven D'Aprano <steve at pearwood.info>
> To: tutor at python.org
> Subject: Re: [Tutor] Contents of Tutor digest, help with Hangman
>        program
> Message-ID: <201007200054.57927.steve at pearwood.info>
> Content-Type: text/plain;  charset="utf-8"
>
> On Mon, 19 Jul 2010 09:37:25 pm John Palmer wrote:
> > Hi Alan thanks for the help. I did try the getpass module, I think I
> > used:
> >
> > getpass.getpass()
> >
> > This actually prompted the user to enter a password, which isn't
> > really what I want. Unless there's something i'm missing with this
> > module? I'll take another look anyway.
>
> Tell the function what prompt to use:
>
> >>> import getpass
> >>> s = getpass.getpass("Please enter your secret word: ")
> Please enter your secret word:
> >>>
> >>> print s
> anti-disestablishmentarianism
>
>
>
> --
> Steven D'Aprano
>
>
> ------------------------------
>
> Message: 6
> Date: Mon, 19 Jul 2010 10:57:11 -0400
> From: bob gailer <bgailer at gmail.com>
> To: John Palmer <speederpython at gmail.com>
> Cc: tutor at python.org
> Subject: Re: [Tutor] Contents of Tutor digest, help with Hangman
>        program
> Message-ID: <4C4467C7.1060701 at gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"; Format="flowed"
>
> On 7/19/2010 7:37 AM, John Palmer wrote:
> > Hi Alan thanks for the help. I did try the getpass module, I think I
> > used:
> >
> > getpass.getpass()
> >
> > This actually prompted the user to enter a password, which isn't
> > really what I want. Unless there's something i'm missing with this
> > module? I'll take another look anyway.
>
> Reading the documentation (15.7 in Python 3):
>
> The getpass module provides two functions:
>
> getpass.getpass(/prompt='Password: '/, /stream=None/)?
> <
> http://docs.python.org/py3k/library/getpass.html?highlight=getpass#getpass.getpass
> >
>
>    Prompt the user for a password without echoing. The user is prompted
>    using the string /prompt/, which defaults to 'Password: '.
>
> HTH
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: <
> http://mail.python.org/pipermail/tutor/attachments/20100719/20256873/attachment-0001.html
> >
>
> ------------------------------
>
> Message: 7
> Date: Tue, 20 Jul 2010 01:01:58 +1000
> From: Steven D'Aprano <steve at pearwood.info>
> To: tutor at python.org
> Subject: Re: [Tutor] A file containing a string of 1 billion random
>        digits.
> Message-ID: <201007200101.58268.steve at pearwood.info>
> Content-Type: text/plain;  charset="iso-8859-1"
>
> On Tue, 20 Jul 2010 12:48:13 am Richard D. Moores wrote:
> > On Mon, Jul 19, 2010 at 07:14, ALAN GAULD <alan.gauld at btinternet.com>
> wrote:
> > >> 4 and executed many times. Seems the 0 in 0dddd is
> > >> there when a dddd is a 3-digit number such as 123.
> > >> In that case a zero is prefixed to 123 to produce
> > >> 0123. Or if just 23, 2 zeros are prefixed, etc.
> > >> Correct?
> > >
> > > Yes, the zero indicates that the string should be padded
> > > with zeros to the length specified. The format string
> > > documentation gives all the details
> >
> > I've been unable to find any mention of that use of the asterisk in
> > the 3.1 docs, in
> >
> > http://docs.python.org/py3k/library/string.html#formatspec
> >
> > or
> >
> > http://docs.python.org/py3k/library/string.html#formatstrings
> >
> > Suggestion?
>
> You're looking in the wrong place. This is not part of format strings,
> as it doesn't use the str.format() method. It uses the % string
> interpolation operator.
>
>
> http://docs.python.org/py3k/library/stdtypes.html#old-string-formatting-operations
>
>
> You can get the same result with the format mini-language. See the
> example "Nested arguments and more complex examples" just before the
> section on Template Strings here:
>
>
> http://docs.python.org/py3k/library/string.html#format-specification-mini-language
>
>
>
>
> --
> Steven D'Aprano
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 77, Issue 70
> *************************************
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100719/fae72cae/attachment-0001.html>

From alan.gauld at btinternet.com  Mon Jul 19 18:58:20 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Mon, 19 Jul 2010 16:58:20 +0000 (GMT)
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com>
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com>
	<201007181101.33483.steve@pearwood.info>
	<4C4342DF.6010404@gmail.com>
	<AANLkTimFilAk6VSxwaUb4ZP_XI_Qdxy7ItK9stldNQXC@mail.gmail.com>
	<i21b5p$9ia$1@dough.gmane.org>
	<AANLkTikR6Q6sQYvrdUb4F1iAfnoMwTtLFGCs978fG6oF@mail.gmail.com>
	<94846.12586.qm@web86706.mail.ird.yahoo.com>
	<AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_@mail.gmail.com>
Message-ID: <835088.68244.qm@web86701.mail.ird.yahoo.com>

Heres what I did:
Search Google for "Python format strings" and from the first link click 
on String Formatting operations in the contents pane:

http://docs.python.org/library/stdtypes.html#string-formatting-operations

Read item number 4.

:-)

 
Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/




----- Original Message ----
> From: Richard D. Moores <rdmoores at gmail.com>
> To: ALAN GAULD <alan.gauld at btinternet.com>
> Cc: tutor at python.org
> Sent: Monday, 19 July, 2010 15:48:13
> Subject: Re: [Tutor] A file containing a string of 1 billion random digits.
> 
> On Mon, Jul 19, 2010 at 07:14, ALAN GAULD <
> ymailto="mailto:alan.gauld at btinternet.com" 
> href="mailto:alan.gauld at btinternet.com">alan.gauld at btinternet.com> 
> wrote:
>
>
>> 4 and executed many times. Seems the 0 in 
> 0dddd is
>> there when a dddd is a 3-digit number such as 
> 123.
>> In that case a zero is prefixed to 123 to produce
>> 
> 0123. Or if just 23, 2 zeros are prefixed, etc.
>> 
> Correct?
>
> Yes, the zero indicates that the string should be 
> padded
> with zeros to the length specified. The format string
> 
> documentation gives all the details

I've been unable to find any mention 
> of that use of the asterisk in
the 3.1 docs, in


> href="http://docs.python.org/py3k/library/string.html#formatspec" target=_blank 
> >http://docs.python.org/py3k/library/string.html#formatspec

or


> href="http://docs.python.org/py3k/library/string.html#formatstrings" 
> target=_blank 
> >http://docs.python.org/py3k/library/string.html#formatstrings

Suggestion?

Dick

From benderjacob44 at gmail.com  Mon Jul 19 19:07:42 2010
From: benderjacob44 at gmail.com (Jacob Bender)
Date: Mon, 19 Jul 2010 13:07:42 -0400
Subject: [Tutor] System Window
Message-ID: <AANLkTimzZ5L3Q43SQYK-E_pgvLtB4JG53Way5dqIW24K@mail.gmail.com>

I was wondering if there was a way to program a new window using Tkinter so
that a one-billion digit number could fit, instead of in the system window,
which dumps numbers once they fill up the screen. I know that it would take
me days to read all of the numbers, but that is not my intention. Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100719/15c1c291/attachment.html>

From rdmoores at gmail.com  Mon Jul 19 19:07:47 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Mon, 19 Jul 2010 10:07:47 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <835088.68244.qm@web86701.mail.ird.yahoo.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com> 
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com> 
	<201007181101.33483.steve@pearwood.info> <4C4342DF.6010404@gmail.com> 
	<AANLkTimFilAk6VSxwaUb4ZP_XI_Qdxy7ItK9stldNQXC@mail.gmail.com> 
	<i21b5p$9ia$1@dough.gmane.org>
	<AANLkTikR6Q6sQYvrdUb4F1iAfnoMwTtLFGCs978fG6oF@mail.gmail.com> 
	<94846.12586.qm@web86706.mail.ird.yahoo.com>
	<AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_@mail.gmail.com> 
	<835088.68244.qm@web86701.mail.ird.yahoo.com>
Message-ID: <AANLkTilkMqbMDqO1WYFNJjFPKXN0axbtx631S5s8j5eb@mail.gmail.com>

On Mon, Jul 19, 2010 at 09:58, ALAN GAULD <alan.gauld at btinternet.com> wrote:
> Heres what I did:
> Search Google for "Python format strings" and from the first link click
> on String Formatting operations in the contents pane:
>
> http://docs.python.org/library/stdtypes.html#string-formatting-operations
>
> Read item number 4.

"4. Minimum field width (optional). If specified as an '*' (asterisk),
the actual width is read from the next element of the tuple in values,
and the object to convert comes after the minimum field width and
optional precision."

Now that just screams for about a dozen well-designed illustrative
examples, don't you think?

Thanks, Alan.

From alan.gauld at btinternet.com  Mon Jul 19 19:18:39 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Mon, 19 Jul 2010 17:18:39 +0000 (GMT)
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTilkMqbMDqO1WYFNJjFPKXN0axbtx631S5s8j5eb@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com>
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com>
	<201007181101.33483.steve@pearwood.info>
	<4C4342DF.6010404@gmail.com>
	<AANLkTimFilAk6VSxwaUb4ZP_XI_Qdxy7ItK9stldNQXC@mail.gmail.com>
	<i21b5p$9ia$1@dough.gmane.org>
	<AANLkTikR6Q6sQYvrdUb4F1iAfnoMwTtLFGCs978fG6oF@mail.gmail.com>
	<94846.12586.qm@web86706.mail.ird.yahoo.com>
	<AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_@mail.gmail.com>
	<835088.68244.qm@web86701.mail.ird.yahoo.com>
	<AANLkTilkMqbMDqO1WYFNJjFPKXN0axbtx631S5s8j5eb@mail.gmail.com>
Message-ID: <274430.80650.qm@web86701.mail.ird.yahoo.com>

Wikipedia is a little more helpful but not Python oriented:

http://en.wikipedia.org/wiki/Printf#printf_format_placeholders

 
Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/




----- Original Message ----
> From: Richard D. Moores <rdmoores at gmail.com>
> To: ALAN GAULD <alan.gauld at btinternet.com>
> Cc: tutor at python.org
> Sent: Monday, 19 July, 2010 18:07:47
> Subject: Re: [Tutor] A file containing a string of 1 billion random digits.
> 
> On Mon, Jul 19, 2010 at 09:58, ALAN GAULD <
> ymailto="mailto:alan.gauld at btinternet.com" 
> href="mailto:alan.gauld at btinternet.com">alan.gauld at btinternet.com> 
> wrote:
> Heres what I did:
> Search Google for "Python format 
> strings" and from the first link click
> on String Formatting operations 
> in the contents pane:
>
> 
> href="http://docs.python.org/library/stdtypes.html#string-formatting-operations" 
> target=_blank 
> >http://docs.python.org/library/stdtypes.html#string-formatting-operations
>
> 
> Read item number 4.

"4. Minimum field width (optional). If specified as 
> an '*' (asterisk),
the actual width is read from the next element of the 
> tuple in values,
and the object to convert comes after the minimum field 
> width and
optional precision."

Now that just screams for about a dozen 
> well-designed illustrative
examples, don't you think?

Thanks, 
> Alan.

From alan.gauld at btinternet.com  Mon Jul 19 19:42:15 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Jul 2010 18:42:15 +0100
Subject: [Tutor] A file containing a string of 1 billion random digits.
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<94846.12586.qm@web86706.mail.ird.yahoo.com><AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_@mail.gmail.com>
	<201007200101.58268.steve@pearwood.info>
	<AANLkTineoXcQ59R03sXpoxNyGYsSIASRq_s80DgwOPmf@mail.gmail.com>
Message-ID: <i222pj$39d$1@dough.gmane.org>


"Richard D. Moores" <rdmoores at gmail.com> wrote

> The formatting operations described here are obsolete and may go 
> away
> in future versions of Python. Use the new String Formatting in new
> code.
>
> I hope that use of '*' does disappear. It's the most confusing thing
> I've recently tried to get my mind around!

But knowing C's printf style formatting is almost a necessary skill
for a programmer because they are used in lots of lamguages
not just Python. So you would only need to learn them later is all! 
:-)

Note: This is one reason I decided to stick with the % format strings
in my v3 tutor - I'nm aiming to teach generic skills and % formatting
is much more generic than the new Python style formatting. (And
much less verbose!)

> Before that, maybe, was the Trinity..

Nah, that still wins - a divine mystery :-)

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



From alan.gauld at btinternet.com  Mon Jul 19 19:46:24 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Jul 2010 18:46:24 +0100
Subject: [Tutor] Contents of Tutor digest, help with Hangman program
References: <AANLkTinfQmnIJxwiQfAMYgVSwNnNqtblgcA7GW7h42vF@mail.gmail.com>
Message-ID: <i2231c$454$1@dough.gmane.org>


"John Palmer" <speederpython at gmail.com> wrote

Please trim your messages and not post the entire digest.

> Hi Alan thanks for the help. I did try the getpass module, I think I 
> used:
>
> getpass.getpass()
>
> This actually prompted the user to enter a password, which isn't 
> really what
> I want. Unless there's something i'm missing with this module?

like raw_input you can supply a prompt to getpass()

>>> import getpass as gp
>>> gp.getpass()
Password:
'gghg'
>>> gp.getpass("Number?")
Number?
'hjggjkh'
>>>

HTH,


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



From timomlists at gmail.com  Mon Jul 19 19:54:13 2010
From: timomlists at gmail.com (Timo)
Date: Mon, 19 Jul 2010 19:54:13 +0200
Subject: [Tutor] Contents of Tutor digest, Help with hangman
In-Reply-To: <AANLkTikK9uhSyztcNoLWWs-C_RgiUa6qc1P1XD3__P6b@mail.gmail.com>
References: <AANLkTikK9uhSyztcNoLWWs-C_RgiUa6qc1P1XD3__P6b@mail.gmail.com>
Message-ID: <4C449145.7000402@gmail.com>

On 19-07-10 18:20, John Palmer wrote:
> Thanks a lot for the help guys, but when I use the 
> getpass.getpass(Enter your word here, I get a different response to 
> what you get. This is what happen with mine:
>
> >>> import getpass
> >>> s = getpass.getpass("Enter your word here: ")
> Warning: Password input may be echoed.
> Please enter your secret word: hangman
>
> >>> s
> 'hangman'
> >>>
This may not be really helpful, but I am using Ubuntu 10.04 too and have 
no problems. Running in the Gnome terminal:

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import getpass
 >>> s = getpass.getpass("Enter your word here: ")
Enter your word here:
 >>> print s
blah

Cheers,
Timo

>
>
> I'm guessing that its something to do with the "Warning: Password may 
> be echoed" line. In the documentation it says:
>
> "If echo free input is unavailable getpass() falls back to printing a 
> warning message to stream and reading
> from sys.stdin and issuing a GetPassWarning."
>
> But i'm not sure what that means, sry to be a pain, and again thanks 
> for all the help.
>
> I did manage to find another solution which is just to print a large 
> number of blank lines, which just moved the line with the word in it 
> off the screen, but I don't really like it to be honest. The getpass 
> module seems to be the best solution i just don't understand why its 
> not working for me.
>
> Regards
> John
>
>
>
> On 19 July 2010 16:02, <tutor-request at python.org 
> <mailto:tutor-request at python.org>> wrote:
>
>     Send Tutor mailing list submissions to
>     tutor at python.org <mailto:tutor at python.org>
>
>     To subscribe or unsubscribe via the World Wide Web, visit
>     http://mail.python.org/mailman/listinfo/tutor
>     or, via email, send a message with subject or body 'help' to
>     tutor-request at python.org <mailto:tutor-request at python.org>
>
>     You can reach the person managing the list at
>     tutor-owner at python.org <mailto:tutor-owner at python.org>
>
>     When replying, please edit your Subject line so it is more specific
>     than "Re: Contents of Tutor digest..."
>
>
>     Today's Topics:
>
>       1. Re: A file containing a string of 1 billion random digits.
>          (Peter Otten)
>       2. Re: A file containing a string of 1 billion random digits.
>          (ALAN GAULD)
>       3. Re: A file containing a string of 1 billion random digits.
>          (Richard D. Moores)
>       4. Re: A file containing a string of 1 billion random digits.
>          (Richard D. Moores)
>       5. Re: Contents of Tutor digest, help with Hangman program
>          (Steven D'Aprano)
>       6. Re: Contents of Tutor digest, help with Hangman program
>          (bob gailer)
>       7. Re: A file containing a string of 1 billion random digits.
>          (Steven D'Aprano)
>
>
>     ----------------------------------------------------------------------
>
>     Message: 1
>     Date: Mon, 19 Jul 2010 15:45:43 +0200
>     From: Peter Otten <__peter__ at web.de <mailto:peter__ at web.de>>
>     To: tutor at python.org <mailto:tutor at python.org>
>     Subject: Re: [Tutor] A file containing a string of 1 billion random
>            digits.
>     Message-ID: <i21ku0$e00$1 at dough.gmane.org <mailto:1 at dough.gmane.org>>
>     Content-Type: text/plain; charset="ISO-8859-1"
>
>     Richard D. Moores wrote:
>
>     > On Mon, Jul 19, 2010 at 04:51, Peter Otten <__peter__ at web.de
>     <mailto:peter__ at web.de>> wrote:
>     >> bob gailer wrote:
>     >>
>     >>> Check this out:
>     >>>
>     >>> import random, time
>     >>> s = time.time()
>     >>> cycles = 1000
>     >>> d = "0123456789"*100
>     >>> f = open("numbers.txt", "w")
>     >>> for i in xrange(n):
>     >>> l = []
>     >>> l.extend(random.sample(d, 1000))
>     >>> f.write(''.join(l))
>     >>> f.close()
>     >>> print time.time() - s
>     >>
>     >> Note that this is not random. E. g. the start sequence "0"*101
>     should
>     >> have a likelyhood of 1/10**101 but is impossible to generate
>     with your
>     >> setup.
>     > I not sure exactly what you mean, because I don't fully understand
>     > that '*' (despite Alan's patient explanation), but if you run
>     >
>     > import random
>     > cycles = 100000
>     > d = "0123456789"*10
>     > for i in range(cycles):
>     > l = []
>     > l.extend(random.sample(d, 100))
>     > s = (''.join(l))
>     > if s[:4] == '0101':
>     > print(s)
>     >
>     > You'll see a bunch of strings that begin with "0101"
>     >
>     > Or if you run
>     >
>     > import random
>     > cycles = 50
>     > d = "0123456789"*10
>     > for i in range(cycles):
>     > l = []
>     > l.extend(random.sample(d, 100))
>     > s = (''.join(l))
>     > if s[:1] == '0':
>     > print(s)
>     >
>     > You'll see some that begin with '0'.
>     >
>     > Am I on the right track?
>
>     No. If you fire up your python interpreter you can do
>
>     >>> "0"*10
>     '0000000000'
>
>     i. e. "0"*101 is a sequence of 101 zeros. Because a sample can
>     pick every
>     item in the population only once and there are only 100 zeros, at
>     most 100
>     of them can be drawn, and the more are drawn the less likely it
>     becomes that
>     another one is drawn. The simplest demo is probably
>
>     random.sample([0, 1], 2)
>
>     Possible returns are [0, 1] and [1, 0], but for true randomness
>     you want [1,
>     1] and [0, 0], too. The more often the items are repeated the less
>     pronounced that bias becomes, e. g.
>
>     random.sample([0, 1, 0, 1], 2)
>
>     can produce all combinations, but [0, 1] is twice as likely as [0, 0]
>     because once the first 0 is drawn there is only one 0 left, but
>     two 1s.
>     Here's a demonstration:
>
>     >>> from collections import defaultdict
>     >>> d = defaultdict(int)
>     >>> for i in range(1000):
>     ...     d[tuple(random.sample([0, 1]*2, 2))] += 1
>     ...
>     >>> dict(d)
>     {(0, 1): 333, (1, 0): 308, (0, 0): 174, (1, 1): 185}
>
>     Peter
>
>
>
>     ------------------------------
>
>     Message: 2
>     Date: Mon, 19 Jul 2010 07:14:18 -0700 (PDT)
>     From: ALAN GAULD <alan.gauld at btinternet.com
>     <mailto:alan.gauld at btinternet.com>>
>     To: "Richard D. Moores" <rdmoores at gmail.com
>     <mailto:rdmoores at gmail.com>>
>     Cc: tutor at python.org <mailto:tutor at python.org>
>     Subject: Re: [Tutor] A file containing a string of 1 billion random
>            digits.
>     Message-ID: <94846.12586.qm at web86706.mail.ird.yahoo.com
>     <mailto:94846.12586.qm at web86706.mail.ird.yahoo.com>>
>     Content-Type: text/plain; charset=utf-8
>
>
>
>     > 4 and executed many times. Seems the 0 in 0dddd is
>     > there when a dddd is a 3-digit number such as 123.
>     > In that case a zero is prefixed to 123 to produce
>     > 0123. Or if just 23, 2 zeros are prefixed, etc.
>     > Correct?
>
>     Yes, the zero indicates that the string should be padded
>     with zeros to the length specified. The format string
>     documentation gives all the details but while zero
>     padding is fairly common the asterisk is less so, that's
>     why I explained it but not the zero...I assumed it was
>     the asterisk that was confusing you...
>
>     HTH,
>
>     Alan G.
>
>
>
>     ------------------------------
>
>     Message: 3
>     Date: Mon, 19 Jul 2010 07:14:13 -0700
>     From: "Richard D. Moores" <rdmoores at gmail.com
>     <mailto:rdmoores at gmail.com>>
>     To: Peter Otten <__peter__ at web.de <mailto:peter__ at web.de>>
>     Cc: tutor at python.org <mailto:tutor at python.org>
>     Subject: Re: [Tutor] A file containing a string of 1 billion random
>            digits.
>     Message-ID:
>     <AANLkTikctB03vyzHhhvmpg8Hrf6lMhRDIGbtKcoNPcn- at mail.gmail.com
>     <mailto:AANLkTikctB03vyzHhhvmpg8Hrf6lMhRDIGbtKcoNPcn- at mail.gmail.com>>
>     Content-Type: text/plain; charset=UTF-8
>
>     On Mon, Jul 19, 2010 at 06:45, Peter Otten <__peter__ at web.de
>     <mailto:peter__ at web.de>> wrote:
>
>     > No. If you fire up your python interpreter you can do
>     >
>     >>>> "0"*10
>     > '0000000000'
>
>     Ah, you're absolutely right. Sorry, I misunderstood you and your '*'.
>     Good catch.
>
>     Dick
>
>
>     ------------------------------
>
>     Message: 4
>     Date: Mon, 19 Jul 2010 07:48:13 -0700
>     From: "Richard D. Moores" <rdmoores at gmail.com
>     <mailto:rdmoores at gmail.com>>
>     To: ALAN GAULD <alan.gauld at btinternet.com
>     <mailto:alan.gauld at btinternet.com>>
>     Cc: tutor at python.org <mailto:tutor at python.org>
>     Subject: Re: [Tutor] A file containing a string of 1 billion random
>            digits.
>     Message-ID:
>     <AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_ at mail.gmail.com
>     <mailto:AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_ at mail.gmail.com>>
>     Content-Type: text/plain; charset=UTF-8
>
>     On Mon, Jul 19, 2010 at 07:14, ALAN GAULD
>     <alan.gauld at btinternet.com <mailto:alan.gauld at btinternet.com>> wrote:
>     >
>     >
>     >> 4 and executed many times. Seems the 0 in 0dddd is
>     >> there when a dddd is a 3-digit number such as 123.
>     >> In that case a zero is prefixed to 123 to produce
>     >> 0123. Or if just 23, 2 zeros are prefixed, etc.
>     >> Correct?
>     >
>     > Yes, the zero indicates that the string should be padded
>     > with zeros to the length specified. The format string
>     > documentation gives all the details
>
>     I've been unable to find any mention of that use of the asterisk in
>     the 3.1 docs, in
>
>     http://docs.python.org/py3k/library/string.html#formatspec
>
>     or
>
>     http://docs.python.org/py3k/library/string.html#formatstrings
>
>     Suggestion?
>
>     Dick
>
>
>     ------------------------------
>
>     Message: 5
>     Date: Tue, 20 Jul 2010 00:54:57 +1000
>     From: Steven D'Aprano <steve at pearwood.info
>     <mailto:steve at pearwood.info>>
>     To: tutor at python.org <mailto:tutor at python.org>
>     Subject: Re: [Tutor] Contents of Tutor digest, help with Hangman
>            program
>     Message-ID: <201007200054.57927.steve at pearwood.info
>     <mailto:201007200054.57927.steve at pearwood.info>>
>     Content-Type: text/plain;  charset="utf-8"
>
>     On Mon, 19 Jul 2010 09:37:25 pm John Palmer wrote:
>     > Hi Alan thanks for the help. I did try the getpass module, I think I
>     > used:
>     >
>     > getpass.getpass()
>     >
>     > This actually prompted the user to enter a password, which isn't
>     > really what I want. Unless there's something i'm missing with this
>     > module? I'll take another look anyway.
>
>     Tell the function what prompt to use:
>
>     >>> import getpass
>     >>> s = getpass.getpass("Please enter your secret word: ")
>     Please enter your secret word:
>     >>>
>     >>> print s
>     anti-disestablishmentarianism
>
>
>
>     --
>     Steven D'Aprano
>
>
>     ------------------------------
>
>     Message: 6
>     Date: Mon, 19 Jul 2010 10:57:11 -0400
>     From: bob gailer <bgailer at gmail.com <mailto:bgailer at gmail.com>>
>     To: John Palmer <speederpython at gmail.com
>     <mailto:speederpython at gmail.com>>
>     Cc: tutor at python.org <mailto:tutor at python.org>
>     Subject: Re: [Tutor] Contents of Tutor digest, help with Hangman
>            program
>     Message-ID: <4C4467C7.1060701 at gmail.com
>     <mailto:4C4467C7.1060701 at gmail.com>>
>     Content-Type: text/plain; charset="iso-8859-1"; Format="flowed"
>
>     On 7/19/2010 7:37 AM, John Palmer wrote:
>     > Hi Alan thanks for the help. I did try the getpass module, I think I
>     > used:
>     >
>     > getpass.getpass()
>     >
>     > This actually prompted the user to enter a password, which isn't
>     > really what I want. Unless there's something i'm missing with this
>     > module? I'll take another look anyway.
>
>     Reading the documentation (15.7 in Python 3):
>
>     The getpass module provides two functions:
>
>     getpass.getpass(/prompt='Password: '/, /stream=None/)?
>     <http://docs.python.org/py3k/library/getpass.html?highlight=getpass#getpass.getpass>
>
>        Prompt the user for a password without echoing. The user is
>     prompted
>        using the string /prompt/, which defaults to 'Password: '.
>
>     HTH
>
>     --
>     Bob Gailer
>     919-636-4239
>     Chapel Hill NC
>
>     -------------- next part --------------
>     An HTML attachment was scrubbed...
>     URL:
>     <http://mail.python.org/pipermail/tutor/attachments/20100719/20256873/attachment-0001.html>
>
>     ------------------------------
>
>     Message: 7
>     Date: Tue, 20 Jul 2010 01:01:58 +1000
>     From: Steven D'Aprano <steve at pearwood.info
>     <mailto:steve at pearwood.info>>
>     To: tutor at python.org <mailto:tutor at python.org>
>     Subject: Re: [Tutor] A file containing a string of 1 billion random
>            digits.
>     Message-ID: <201007200101.58268.steve at pearwood.info
>     <mailto:201007200101.58268.steve at pearwood.info>>
>     Content-Type: text/plain;  charset="iso-8859-1"
>
>     On Tue, 20 Jul 2010 12:48:13 am Richard D. Moores wrote:
>     > On Mon, Jul 19, 2010 at 07:14, ALAN GAULD
>     <alan.gauld at btinternet.com <mailto:alan.gauld at btinternet.com>>
>     wrote:
>     > >> 4 and executed many times. Seems the 0 in 0dddd is
>     > >> there when a dddd is a 3-digit number such as 123.
>     > >> In that case a zero is prefixed to 123 to produce
>     > >> 0123. Or if just 23, 2 zeros are prefixed, etc.
>     > >> Correct?
>     > >
>     > > Yes, the zero indicates that the string should be padded
>     > > with zeros to the length specified. The format string
>     > > documentation gives all the details
>     >
>     > I've been unable to find any mention of that use of the asterisk in
>     > the 3.1 docs, in
>     >
>     > http://docs.python.org/py3k/library/string.html#formatspec
>     >
>     > or
>     >
>     > http://docs.python.org/py3k/library/string.html#formatstrings
>     >
>     > Suggestion?
>
>     You're looking in the wrong place. This is not part of format strings,
>     as it doesn't use the str.format() method. It uses the % string
>     interpolation operator.
>
>     http://docs.python.org/py3k/library/stdtypes.html#old-string-formatting-operations
>
>
>     You can get the same result with the format mini-language. See the
>     example "Nested arguments and more complex examples" just before the
>     section on Template Strings here:
>
>     http://docs.python.org/py3k/library/string.html#format-specification-mini-language
>
>
>
>
>     --
>     Steven D'Aprano
>
>
>     ------------------------------
>
>     _______________________________________________
>     Tutor maillist  - Tutor at python.org <mailto:Tutor at python.org>
>     http://mail.python.org/mailman/listinfo/tutor
>
>
>     End of Tutor Digest, Vol 77, Issue 70
>     *************************************
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>    


From alan.gauld at btinternet.com  Mon Jul 19 19:55:30 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Jul 2010 18:55:30 +0100
Subject: [Tutor] searching for multiple strings in line.starswith()
References: <AANLkTimbFhhTie0PoOWUuZC2cXJEErr8j3gF1m3m1cTS@mail.gmail.com>
Message-ID: <i223ie$637$1@dough.gmane.org>


"Bala subramanian" <bala.biophysics at gmail.com> wrote

> I have to extract the line from a file that does not contain a set 
> of
> strings in the start of the line, i wrote the following code.
>
> for index, line in enumerate(myvar.split('\n')):
>    if line.startswith('') not in ['#Cluster','#Centroid','#End']:

line.startswith() returns a boolean result - True or False
Neither of these is in your list so the if test always passes.

You need to apply startwith to each item in your list.
You could use a list comprehension/generator expression
- or find another approach, maybe using slicing?

HTH,

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





From rdmoores at gmail.com  Mon Jul 19 19:58:50 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Mon, 19 Jul 2010 10:58:50 -0700
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <274430.80650.qm@web86701.mail.ird.yahoo.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com> 
	<AANLkTinUajpvDjZRsTEl3LgzCBcfquQoPDtXh13tmcd2@mail.gmail.com> 
	<AANLkTin12t_YVQUpoLDdYJaHyjdQWtCwSiedYVnfvgH7@mail.gmail.com> 
	<201007181101.33483.steve@pearwood.info> <4C4342DF.6010404@gmail.com> 
	<AANLkTimFilAk6VSxwaUb4ZP_XI_Qdxy7ItK9stldNQXC@mail.gmail.com> 
	<i21b5p$9ia$1@dough.gmane.org>
	<AANLkTikR6Q6sQYvrdUb4F1iAfnoMwTtLFGCs978fG6oF@mail.gmail.com> 
	<94846.12586.qm@web86706.mail.ird.yahoo.com>
	<AANLkTinCzLYCJ6aOfPo64KFUV1UeAcnE7bvMhvutZsh_@mail.gmail.com> 
	<835088.68244.qm@web86701.mail.ird.yahoo.com>
	<AANLkTilkMqbMDqO1WYFNJjFPKXN0axbtx631S5s8j5eb@mail.gmail.com> 
	<274430.80650.qm@web86701.mail.ird.yahoo.com>
Message-ID: <AANLkTinug3scJFy4dVHlsDZnszqUapwnJ67vy2IN1YIE@mail.gmail.com>

On Mon, Jul 19, 2010 at 10:18, ALAN GAULD <alan.gauld at btinternet.com> wrote:
> Wikipedia is a little more helpful but not Python oriented:
>
> http://en.wikipedia.org/wiki/Printf#printf_format_placeholders

Yes, that's helpful.

Say, I found a use for that asterisk in this little function I just wrote:
def sig_digits(n,digits):
    """
    Return any real number n to d significant digits.
    """
    return '%.*g' % (digits, n)

n = -12.22345**.978
digits = 5
x = sig_digits(n, digits)
print(x)

OUTPUT: -11.568

Dick

From alan.gauld at btinternet.com  Mon Jul 19 20:00:55 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Jul 2010 19:00:55 +0100
Subject: [Tutor] Help with hangman
References: <AANLkTikK9uhSyztcNoLWWs-C_RgiUa6qc1P1XD3__P6b@mail.gmail.com>
Message-ID: <i223sj$7d7$1@dough.gmane.org>


"John Palmer" <speederpython at gmail.com> wrote

Modifying the subject...
And I repeat, please don't send the whole digest,
delete the excess irrelevant stuff! (see below!)

> Thanks a lot for the help guys, but when I use the 
> getpass.getpass(Enter
> your word here, I get a different response to what you get. This is 
> what
> happen with mine:
>
>>>> import getpass
>>>> s = getpass.getpass("Enter your word here: ")
> Warning: Password input may be echoed.
> Please enter your secret word: hangman
>
> I'm guessing that its something to do with the "Warning: Password 
> may be
> echoed" line. In the documentation it says:
>
> "If echo free input is unavailable getpass() falls back to printing 
> a
> warning message to stream and reading
> from sys.stdin and issuing a GetPassWarning."

What OS and terminal are you using?
It may be possible to enable echo free input...


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



From alan.gauld at btinternet.com  Mon Jul 19 20:03:55 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Jul 2010 19:03:55 +0100
Subject: [Tutor] System Window
References: <AANLkTimzZ5L3Q43SQYK-E_pgvLtB4JG53Way5dqIW24K@mail.gmail.com>
Message-ID: <i22427$83b$1@dough.gmane.org>


"Jacob Bender" <benderjacob44 at gmail.com> wrote

>I was wondering if there was a way to program a new window using 
>Tkinter so
> that a one-billion digit number could fit, instead of in the system 
> window,
> which dumps numbers once they fill up the screen. I know that it 
> would take
> me days to read all of the numbers, but that is not my intention. 
> Thanks!

Yes there are several ways. But for the reasons you state none of them
make much sense!

You could try one or more text widgets. Or a giant label (or 
labels)...

You could use a scolled widget from the Tix module.

You could probably even create a scrolling drop down list...

Alan G 



From rabidpoobear at gmail.com  Mon Jul 19 20:07:00 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 19 Jul 2010 13:07:00 -0500
Subject: [Tutor] searching for multiple strings in line.starswith()
In-Reply-To: <AANLkTimbFhhTie0PoOWUuZC2cXJEErr8j3gF1m3m1cTS@mail.gmail.com>
References: <AANLkTimbFhhTie0PoOWUuZC2cXJEErr8j3gF1m3m1cTS@mail.gmail.com>
Message-ID: <C6AB8FC1-FA92-498D-AD07-9EDD619D17ED@gmail.com>

You are using Line.startswith incorrectly, read the docs on it and see if you can figure out your problem an key us know. Pay attention to the parameters it takes and the values it returns.

Sent from my iPhone

On Jul 19, 2010, at 11:18 AM, Bala subramanian <bala.biophysics at gmail.com> wrote:

> Friends,
> I have to extract the line from a file that does not contain a set of strings in the start of the line, i wrote the following code.
> 
> for index, line in enumerate(myvar.split('\n')):
>     if line.startswith('') not in ['#Cluster','#Centroid','#End']:
>         line=line.split()
>         print line
> 
> The code works without error but it seems that the condition is not applied. What is the correct way of searching for multiple strings at the start of a line.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From joel.goldstick at gmail.com  Mon Jul 19 20:32:49 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 19 Jul 2010 14:32:49 -0400
Subject: [Tutor] searching for multiple strings in line.starswith()
In-Reply-To: <C6AB8FC1-FA92-498D-AD07-9EDD619D17ED@gmail.com>
References: <AANLkTimbFhhTie0PoOWUuZC2cXJEErr8j3gF1m3m1cTS@mail.gmail.com>
	<C6AB8FC1-FA92-498D-AD07-9EDD619D17ED@gmail.com>
Message-ID: <AANLkTimTZITmhEonejnlABqEt9m0C2qgnqt2bouZEcs-@mail.gmail.com>

On Mon, Jul 19, 2010 at 2:07 PM, Luke Paireepinart
<rabidpoobear at gmail.com>wrote:

> You are using Line.startswith incorrectly, read the docs on it and see if
> you can figure out your problem an key us know. Pay attention to the
> parameters it takes and the values it returns.
>
> Sent from my iPhone
>
> On Jul 19, 2010, at 11:18 AM, Bala subramanian <bala.biophysics at gmail.com>
> wrote:
>
> > Friends,
> > I have to extract the line from a file that does not contain a set of
> strings in the start of the line, i wrote the following code.
> >
> > for index, line in enumerate(myvar.split('\n')):
> >     if line.startswith('') not in ['#Cluster','#Centroid','#End']:
> >         line=line.split()
> >         print line
> >
> > The code works without error but it seems that the condition is not
> applied. What is the correct way of searching for multiple strings at the
> start of a line.
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

I recently used this code:

split_line = line.split(' ', 1)

which takes the text from the start up to the first space.

then something like:

if split_line not in [...etc....]
    print split_line
    # or if you want the original line print line





-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100719/5f06d0ac/attachment-0001.html>

From waynejwerner at gmail.com  Mon Jul 19 21:19:46 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Mon, 19 Jul 2010 14:19:46 -0500
Subject: [Tutor] Contents of Tutor digest, Help with hangman
In-Reply-To: <AANLkTikK9uhSyztcNoLWWs-C_RgiUa6qc1P1XD3__P6b@mail.gmail.com>
References: <AANLkTikK9uhSyztcNoLWWs-C_RgiUa6qc1P1XD3__P6b@mail.gmail.com>
Message-ID: <AANLkTinv3tIH-vREl_7ShAMO1b92HU5jdZ13xOPXdmTj@mail.gmail.com>

On Mon, Jul 19, 2010 at 11:20 AM, John Palmer <speederpython at gmail.com>wrote:

> Thanks a lot for the help guys, but when I use the getpass.getpass(Enter
> your word here, I get a different response to what you get. This is what
> happen with mine:
>
> >>> import getpass
> >>> s = getpass.getpass("Enter your word here: ")
> Warning: Password input may be echoed.
> Please enter your secret word: hangman
>
> >>> s
> 'hangman'
> >>>
>
>
> I'm guessing that its something to do with the "Warning: Password may be
> echoed" line. In the documentation it says:
>
> "If echo free input is unavailable getpass() falls back to printing a
> warning message to stream and reading
> from sys.stdin and issuing a GetPassWarning."
> <snip copious amounts of irrelevant reply data>


What terminal emulator are you using? Whatever it is, apparently it doesn't
offer the ability to turn off echoing - or at least it doesn't report such
things. Though AFAIK, xterm, Eterm, and gnome-terminal all are fine with
that.

-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100719/28334f3f/attachment.html>

From speederpython at gmail.com  Mon Jul 19 22:33:16 2010
From: speederpython at gmail.com (John Palmer)
Date: Mon, 19 Jul 2010 21:33:16 +0100
Subject: [Tutor] Contents of Tutor digest, Help with hangman
Message-ID: <AANLkTimP2nrL5KxeDReo46t3Ak669ryyL_dktN1SqBTC@mail.gmail.com>

Right thanks for all the help guys, finally got it working. It was because
as previously suggested, I was using Idle instead of the terminal.

Again thanks for all the help

John
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100719/f291e6fe/attachment.html>

From steve at pearwood.info  Tue Jul 20 01:53:25 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 20 Jul 2010 09:53:25 +1000
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <AANLkTilkMqbMDqO1WYFNJjFPKXN0axbtx631S5s8j5eb@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<835088.68244.qm@web86701.mail.ird.yahoo.com>
	<AANLkTilkMqbMDqO1WYFNJjFPKXN0axbtx631S5s8j5eb@mail.gmail.com>
Message-ID: <201007200953.25686.steve@pearwood.info>

On Tue, 20 Jul 2010 03:07:47 am Richard D. Moores wrote:
> On Mon, Jul 19, 2010 at 09:58, ALAN GAULD <alan.gauld at btinternet.com> 
wrote:
> > Heres what I did:
> > Search Google for "Python format strings" and from the first link
> > click on String Formatting operations in the contents pane:
> >
> > http://docs.python.org/library/stdtypes.html#string-formatting-oper
> >ations
> >
> > Read item number 4.
>
> "4. Minimum field width (optional). If specified as an '*'
> (asterisk), the actual width is read from the next element of the
> tuple in values, and the object to convert comes after the minimum
> field width and optional precision."
>
> Now that just screams for about a dozen well-designed illustrative
> examples, don't you think?

Surely it only needs one?

(a) Field width known when you write the template, compared to (b) it 
being unknown when you write the template:

>>> template = "(a) %05d | (b) %0*d"
>>> template % (42, 5, 42)
'(a) 00042 | (b) 00042'


This is how you would do it with the asterisk: you need a meta-template 
to make a template.

>>> meta = "(a) %%05d | (b) %%0%dd"
>>> template = meta % 5
>>> template % (42, 42)
'(a) 00042 | (b) 00042'




-- 
Steven D'Aprano

From steve at pearwood.info  Tue Jul 20 01:58:41 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 20 Jul 2010 09:58:41 +1000
Subject: [Tutor] A file containing a string of 1 billion random digits.
In-Reply-To: <201007200953.25686.steve@pearwood.info>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<AANLkTilkMqbMDqO1WYFNJjFPKXN0axbtx631S5s8j5eb@mail.gmail.com>
	<201007200953.25686.steve@pearwood.info>
Message-ID: <201007200958.41235.steve@pearwood.info>

On Tue, 20 Jul 2010 09:53:25 am Steven D'Aprano wrote:

> This is how you would do it with the asterisk: you need a
> meta-template to make a template.

Doh! I meant *without* the asterisk.

> >>> meta = "(a) %%05d | (b) %%0%dd"
> >>> template = meta % 5
> >>> template % (42, 42)
>
> '(a) 00042 | (b) 00042'



-- 
Steven D'Aprano

From steve at pearwood.info  Tue Jul 20 02:57:12 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 20 Jul 2010 10:57:12 +1000
Subject: [Tutor] [OT] Confusion [was Re: A file containing a string of 1
	billion random digits.]
In-Reply-To: <AANLkTineoXcQ59R03sXpoxNyGYsSIASRq_s80DgwOPmf@mail.gmail.com>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<201007200101.58268.steve@pearwood.info>
	<AANLkTineoXcQ59R03sXpoxNyGYsSIASRq_s80DgwOPmf@mail.gmail.com>
Message-ID: <201007201057.13152.steve@pearwood.info>

On Tue, 20 Jul 2010 01:42:51 am Richard D. Moores wrote:

> The formatting operations described here are obsolete and may go away
> in future versions of Python. Use the new String Formatting in new
> code.
>
> I hope that use of '*' does disappear. It's the most confusing thing
> I've recently tried to get my mind around! 

If you think that's confusing, you should try reading up on Monads.

http://en.wikipedia.org/wiki/Monad_(functional_programming)


> Before that, maybe, was the Trinity..

[Note: the following may be offensive to some Christians, in which case, 
remember that nobody has the right to not be offended, and nobody is 
forcing you to read on.]

The Trinity is simple to understand once you realise one thing -- 
despite all the obfuscatory pseudo-justifications for it, it is not 
meant to be understood, it's meant to be believed. It is a Mystery, 
something beyond human understanding. Not merely a small-m mystery, 
something which is possible to understand in principle, if we only knew 
enough. As Tertullian said (in a related but slightly different 
context):

"It is certain because it is impossible". 

Or, to paraphrase, "I believe it because it is absurd".

Like many religious beliefs (e.g. transubstantiation and dietary 
restrictions), belief in the Trinity is a shibboleth. Belief in the 
Trinity distinguishes Us ("true Christians") from Them (heretics and 
pagans[1]). The more ridiculous and crazy the belief, the more 
effective it is as a shibboleth. Anyone can believe that the son and 
the father are different people, because that's just ordinary 
common-sense[2]. But to believe that the son and the father are one and 
the same while being different *at the same time* makes no sense. It 
is, as Tertullian would almost certainly have admitted, absurd and 
ridiculous and totally crazy. Tertullian would have believed it 
*because* it was unbelievable.

It really is frightening to realise that, essentially, the Chewbacca 
Defence has held such a grip on human society for so many centuries.

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




[1] Actually many pagans also believe in trinities. But they believe in 
the *wrong* trinity: the three-as-one nature of Brahma/Vishnu/Shiva,  
Ra/Horus/Osiris, Ceres/Liber/Libera, or (two-in-one) Apollo/Bacchus is 
mere pagan superstition, while the three-as-one nature of 
Father/Son/Spirit is self-evidently true, at least according to those 
Christian sects which believe in a trinity.

[2] So rare that it ought to count as a superpower.


-- 
Steven D'Aprano

From smokefloat at gmail.com  Tue Jul 20 03:23:32 2010
From: smokefloat at gmail.com (David Hutto)
Date: Mon, 19 Jul 2010 21:23:32 -0400
Subject: [Tutor] [OT] Confusion [was Re: A file containing a string of 1
	billion random digits.]
In-Reply-To: <201007201057.13152.steve@pearwood.info>
References: <AANLkTikWOxVT9M4cDL8wI6iU8PR6b_PaPjcq8plKopi6@mail.gmail.com>
	<201007200101.58268.steve@pearwood.info>
	<AANLkTineoXcQ59R03sXpoxNyGYsSIASRq_s80DgwOPmf@mail.gmail.com>
	<201007201057.13152.steve@pearwood.info>
Message-ID: <AANLkTilwcCvWSJelXzwvnU5gH8n5aKimwbQnak7BvFkd@mail.gmail.com>

On Mon, Jul 19, 2010 at 8:57 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, 20 Jul 2010 01:42:51 am Richard D. Moores wrote:
>
>> The formatting operations described here are obsolete and may go away
>> in future versions of Python. Use the new String Formatting in new
>> code.
>>
>> I hope that use of '*' does disappear. It's the most confusing thing
>> I've recently tried to get my mind around!
>
> If you think that's confusing, you should try reading up on Monads.
>
> http://en.wikipedia.org/wiki/Monad_(functional_programming)
>
>
>> Before that, maybe, was the Trinity..
>
> [Note: the following may be offensive to some Christians, in which case,
> remember that nobody has the right to not be offended, and nobody is
> forcing you to read on.]
>
> The Trinity is simple to understand once you realise one thing --
> despite all the obfuscatory pseudo-justifications for it, it is not
> meant to be understood, it's meant to be believed.

It is meant to be understood, and it is understood, yet man has
attachments to an 'earthly' realm, which leads to a hinderance in the
principles given to guide them...to be all Zen about it.




It is a Mystery,
> something beyond human understanding. Not merely a small-m mystery,
> something which is possible to understand in principle, if we only knew
> enough. As Tertullian said (in a related but slightly different
> context):
>
> "It is certain because it is impossible".
>
> Or, to paraphrase, "I believe it because it is absurd".
>
> Like many religious beliefs (e.g. transubstantiation and dietary
> restrictions), belief in the Trinity is a shibboleth. Belief in the
> Trinity distinguishes Us ("true Christians") from Them (heretics and
> pagans[1]). The more ridiculous and crazy the belief, the more
> effective it is as a shibboleth. Anyone can believe that the son and
> the father are different people, because that's just ordinary
> common-sense[2]. But to believe that the son and the father are one and
> the same while being different *at the same time* makes no sense.

Think of the parent child windows, while one is the master the slave
has limitations, but still can display the 'words' of the parent.

 It
> is, as Tertullian would almost certainly have admitted, absurd and
> ridiculous and totally crazy. Tertullian would have believed it
> *because* it was unbelievable.

Debate 101 can cause men to take strange stances in order to perfect
their arguments.


>
> It really is frightening to realise that, essentially, the Chewbacca
> Defence has held such a grip on human society for so many centuries.

Haven't read it yet, but will get to it eventually.
>
> http://en.wikipedia.org/wiki/Chewbacca_defense
>
>
>
>
> [1] Actually many pagans also believe in trinities. But they believe in
> the *wrong* trinity: the three-as-one nature of Brahma/Vishnu/Shiva,
> Ra/Horus/Osiris, Ceres/Liber/Libera, or (two-in-one) Apollo/Bacchus is
> mere pagan superstition,
Who can really say what is and what isn't, if your stance above is
that [It] is undefinable and a mystery to man.

 while the three-as-one nature of
> Father/Son/Spirit is self-evidently true, at least according to those
> Christian sects which believe in a trinity.
>
> [2] So rare that it ought to count as a superpower.

Anyone can believe that the son and
> the father are different people, because that's just ordinary
> common-sense[2]

How does this relate?

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

From pine508 at hotmail.com  Tue Jul 20 06:48:19 2010
From: pine508 at hotmail.com (Che M)
Date: Tue, 20 Jul 2010 00:48:19 -0400
Subject: [Tutor] SQLite database locked problem
Message-ID: <SNT127-W1521734F12D1EFD7951017E0A00@phx.gbl>


I'm using an SQLite3 database (with Python 2.5) and every so often the application crashes or hangs because somewhere there is this error, or something like it:

OperationalError:  database is locked.

This is probably because I am viewing and sometimes changing the database through SQLite Database Browser while working on my app, and occasionally the app tries to access the db when the Database Browser is writing to it or something like that.    

I'd like to a) know how to reproduce the error (haven't seen it in a while, but want to be sure  know when it may happen for users and b) prevent it from being a problem in the running app.  

Any suggestions welcome.  Thank you,
Che
 		 	   		  
_________________________________________________________________
Hotmail is redefining busy with tools for the New Busy. Get more from your inbox.
http://www.windowslive.com/campaign/thenewbusy?ocid=PID28326::T:WLMTAGL:ON:WL:en-US:WM_HMP:042010_2
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100720/cc89ff17/attachment.html>

From cwitts at compuscan.co.za  Tue Jul 20 07:28:45 2010
From: cwitts at compuscan.co.za (Christian Witts)
Date: Tue, 20 Jul 2010 07:28:45 +0200
Subject: [Tutor] SQLite database locked problem
In-Reply-To: <SNT127-W1521734F12D1EFD7951017E0A00@phx.gbl>
References: <SNT127-W1521734F12D1EFD7951017E0A00@phx.gbl>
Message-ID: <4C45340D.9020704@compuscan.co.za>

On 20/07/2010 06:48, Che M wrote:
> I'm using an SQLite3 database (with Python 2.5) and every so often the 
> application crashes or hangs because somewhere there is this error, or 
> something like it:
>
> OperationalError:  database is locked.
>
> This is probably because I am viewing and sometimes changing the 
> database through SQLite Database Browser while working on my app, and 
> occasionally the app tries to access the db when the Database Browser 
> is writing to it or something like that.
>
> I'd like to a) know how to reproduce the error (haven't seen it in a 
> while, but want to be sure  know when it may happen for users and b) 
> prevent it from being a problem in the running app.
>
> Any suggestions welcome.  Thank you,
> Che
>
> ------------------------------------------------------------------------
> Hotmail is redefining busy with tools for the New Busy. Get more from 
> your inbox. See how. 
> <http://www.windowslive.com/campaign/thenewbusy?ocid=PID28326::T:WLMTAGL:ON:WL:en-US:WM_HMP:042010_2> 
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>    

SQLite is technically thread safe, but a write operation locks the 
entire database [1]:
- Any resultset being step()'d through uses a shared read-only lock.
- Any insert/update being executed requires an exclusive write lock.

[1] http://www.sqlite.org/lockingv3.html

-- 
Kind Regards,
Christian Witts


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100720/858c974d/attachment.html>

From alan.gauld at btinternet.com  Wed Jul 21 19:55:25 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 21 Jul 2010 18:55:25 +0100
Subject: [Tutor] has it gone quiet or is it just me?
Message-ID: <i27cac$uct$1@dough.gmane.org>

I haven't had any tutor messages in 2 days.
Do I have a problem or are things just very quiet suddenly?
The archive isn't showing anything either which makes me suspicious.


From rabidpoobear at gmail.com  Wed Jul 21 20:04:41 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 21 Jul 2010 13:04:41 -0500
Subject: [Tutor] has it gone quiet or is it just me?
In-Reply-To: <i27cac$uct$1@dough.gmane.org>
References: <i27cac$uct$1@dough.gmane.org>
Message-ID: <AANLkTingeyvwYBXkJjFDd7kG64ldp_YPGqvs8B2zPkgj@mail.gmail.com>

Not sure Alan.
I haven't gotten any messages either, but this one came through just fine.
-Luke

On Wed, Jul 21, 2010 at 12:55 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> I haven't had any tutor messages in 2 days.
> Do I have a problem or are things just very quiet suddenly?
> The archive isn't showing anything either which makes me suspicious.
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From david at pythontoo.com  Wed Jul 21 20:10:11 2010
From: david at pythontoo.com (David Abbott)
Date: Wed, 21 Jul 2010 14:10:11 -0400
Subject: [Tutor] has it gone quiet or is it just me?
In-Reply-To: <i27cac$uct$1@dough.gmane.org>
References: <i27cac$uct$1@dough.gmane.org>
Message-ID: <AANLkTi=hyqQnv9z4yDSH39Ttn4qX2hOvcwXzA8HpFyb+@mail.gmail.com>

On Wed, Jul 21, 2010 at 1:55 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> I haven't had any tutor messages in 2 days.
> Do I have a problem or are things just very quiet suddenly?
> The archive isn't showing anything either which makes me suspicious.
>
Hi Alan,
Sorry have not been paying attention, but did get this as you I hope can see :)
David

-- 
David Abbott (dabbott)

From alan.gauld at btinternet.com  Wed Jul 21 20:14:01 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 21 Jul 2010 19:14:01 +0100
Subject: [Tutor] has it gone quiet or is it just me?
References: <i27cac$uct$1@dough.gmane.org>
Message-ID: <i27dd7$2ul$1@dough.gmane.org>

OK, from the fact I got two replies and Luke hasn't had anything 
either
I'll assume all is ok and things are just quiet :-)


"Alan Gauld" <alan.gauld at btinternet.com> wrote in message 
news:i27cac$uct$1 at dough.gmane.org...
>I haven't had any tutor messages in 2 days.
> Do I have a problem or are things just very quiet suddenly?
> The archive isn't showing anything either which makes me suspicious.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 



From yam at nerd.cx  Wed Jul 21 20:03:51 2010
From: yam at nerd.cx (William Witteman)
Date: Wed, 21 Jul 2010 14:03:51 -0400
Subject: [Tutor] has it gone quiet or is it just me?
In-Reply-To: <i27cac$uct$1@dough.gmane.org>
References: <i27cac$uct$1@dough.gmane.org>
Message-ID: <20100721180351.GA1469@yam.witteman.ca>

On Wed, Jul 21, 2010 at 06:55:25PM +0100, Alan Gauld wrote:
>I haven't had any tutor messages in 2 days.
>Do I have a problem or are things just very quiet suddenly?
>The archive isn't showing anything either which makes me suspicious.

It's not just you.  I've been hearing crickets as well.
-- 

yours,

William


From anand.shashwat at gmail.com  Wed Jul 21 20:15:45 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Wed, 21 Jul 2010 23:45:45 +0530
Subject: [Tutor] has it gone quiet or is it just me?
In-Reply-To: <i27dd7$2ul$1@dough.gmane.org>
References: <i27cac$uct$1@dough.gmane.org> <i27dd7$2ul$1@dough.gmane.org>
Message-ID: <AANLkTik5uJejufbxnO3NL8fkLTMxcy6n-XkZGIQmravy@mail.gmail.com>

On Wed, Jul 21, 2010 at 11:44 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> OK, from the fact I got two replies and Luke hasn't had anything either
> I'll assume all is ok and things are just quiet :-)
>

Yes. c-l-p is having decent traffic though.


>
>
> "Alan Gauld" <alan.gauld at btinternet.com> wrote in message
> news:i27cac$uct$1 at dough.gmane.org...
>
>  I haven't had any tutor messages in 2 days.
>> Do I have a problem or are things just very quiet suddenly?
>> The archive isn't showing anything either which makes me suspicious.
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100721/44a888a4/attachment.html>

From hugo.yoshi at gmail.com  Wed Jul 21 20:26:50 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Wed, 21 Jul 2010 20:26:50 +0200
Subject: [Tutor] has it gone quiet or is it just me?
In-Reply-To: <i27dd7$2ul$1@dough.gmane.org>
References: <i27cac$uct$1@dough.gmane.org> <i27dd7$2ul$1@dough.gmane.org>
Message-ID: <AANLkTilHCU1CI6xHvqzXG7-vVpV7yFSUIuNx0CHQ4jWF@mail.gmail.com>

Damnit guys, I was hoping everyone would stay real quiet so we could
freak Alan out a bit ;-)

On Wed, Jul 21, 2010 at 8:14 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> OK, from the fact I got two replies and Luke hasn't had anything either
> I'll assume all is ok and things are just quiet :-)
>
>
> "Alan Gauld" <alan.gauld at btinternet.com> wrote in message
> news:i27cac$uct$1 at dough.gmane.org...
>>
>> I haven't had any tutor messages in 2 days.
>> Do I have a problem or are things just very quiet suddenly?
>> The archive isn't showing anything either which makes me suspicious.
>>
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From lowelltackett at yahoo.com  Wed Jul 21 20:32:02 2010
From: lowelltackett at yahoo.com (Lowell Tackett)
Date: Wed, 21 Jul 2010 11:32:02 -0700 (PDT)
Subject: [Tutor] has it gone quiet or is it just me?
In-Reply-To: <i27cac$uct$1@dough.gmane.org>
Message-ID: <205532.75434.qm@web110104.mail.gq1.yahoo.com>

You folks are just so good at what you do here that you've answered everybody's questions.  Everyone's happy right now.
>From the virtual desk of Lowell Tackett  



--- On Wed, 7/21/10, Alan Gauld <alan.gauld at btinternet.com> wrote:

> From: Alan Gauld <alan.gauld at btinternet.com>
> Subject: [Tutor] has it gone quiet or is it just me?
> To: tutor at python.org
> Date: Wednesday, July 21, 2010, 1:55 PM
> I haven't had any tutor messages in 2
> days.
> Do I have a problem or are things just very quiet
> suddenly?
> The archive isn't showing anything either which makes me
> suspicious.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 


      


From kb1pkl at aim.com  Wed Jul 21 20:34:09 2010
From: kb1pkl at aim.com (Corey Richardson)
Date: Wed, 21 Jul 2010 14:34:09 -0400
Subject: [Tutor] has it gone quiet or is it just me?
In-Reply-To: <i27cac$uct$1@dough.gmane.org>
References: <i27cac$uct$1@dough.gmane.org>
Message-ID: <4C473DA1.70208@aim.com>

The "SQLite Database locked problem" was yesterday at 12:48 AM, I'm 
guessing you didn't count that? ;)

Alan Gauld wrote:
> I haven't had any tutor messages in 2 days.
> Do I have a problem or are things just very quiet suddenly?
> The archive isn't showing anything either which makes me suspicious.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From bermanrl at cfl.rr.com  Wed Jul 21 20:13:04 2010
From: bermanrl at cfl.rr.com (Robert Berman)
Date: Wed, 21 Jul 2010 14:13:04 -0400
Subject: [Tutor] has it gone quiet or is it just me?
In-Reply-To: <AANLkTingeyvwYBXkJjFDd7kG64ldp_YPGqvs8B2zPkgj@mail.gmail.com>
References: <i27cac$uct$1@dough.gmane.org>
	<AANLkTingeyvwYBXkJjFDd7kG64ldp_YPGqvs8B2zPkgj@mail.gmail.com>
Message-ID: <000c01cb2900$5d3da150$17b8e3f0$@rr.com>

Same.

Robert

> -----Original Message-----
> From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor-
> bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Luke
> Paireepinart
> Sent: Wednesday, July 21, 2010 2:05 PM
> To: Alan Gauld
> Cc: tutor at python.org
> Subject: Re: [Tutor] has it gone quiet or is it just me?
> 
> Not sure Alan.
> I haven't gotten any messages either, but this one came through just
> fine.
> -Luke
> 
> On Wed, Jul 21, 2010 at 12:55 PM, Alan Gauld
> <alan.gauld at btinternet.com> wrote:
> > I haven't had any tutor messages in 2 days.
> > Do I have a problem or are things just very quiet suddenly?
> > The archive isn't showing anything either which makes me
> suspicious.
> >
> > _______________________________________________
> > Tutor maillist ?- ?Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> >
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From chombee at lavabit.com  Wed Jul 21 22:14:03 2010
From: chombee at lavabit.com (chombee)
Date: Wed, 21 Jul 2010 21:14:03 +0100
Subject: [Tutor] Observer design pattern: request for feedback
Message-ID: <20100721201403.GA7352@kisimul>

Hi,

I decided I wanted to use the Observer design pattern in my application.
I did a little googling, but all the examples that I found of Observer
in Python seemed over-complicated, so I wrote my own simple version. It
doesn't have as many features as other Observer implementations might,
but it's a start. Any critical comments or suggestions would be greatly
appreciated. The code is here:

https://gist.github.com/90d8b7ec425ac92f5539


From mehgcap at gmail.com  Thu Jul 22 05:08:56 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Wed, 21 Jul 2010 23:08:56 -0400
Subject: [Tutor] attachments?
Message-ID: <AANLkTilmTgNoqOwVlUi18IXRfjUc0KCpdKgyTbITN27h@mail.gmail.com>

-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From pine508 at hotmail.com  Thu Jul 22 05:46:19 2010
From: pine508 at hotmail.com (Che M)
Date: Wed, 21 Jul 2010 23:46:19 -0400
Subject: [Tutor] SQLite database locked problem
In-Reply-To: <4C45340D.9020704@compuscan.co.za>
References: <SNT127-W1521734F12D1EFD7951017E0A00@phx.gbl>,
	<4C45340D.9020704@compuscan.co.za>
Message-ID: <SNT127-W97C387D378F12C67EE5C0E0A20@phx.gbl>




Date: Tue, 20 Jul 2010 07:28:45 +0200
From: cwitts at compuscan.co.za
To: pine508 at hotmail.com
CC: tutor at python.org
Subject: Re: [Tutor] SQLite database locked problem






  
  


On 20/07/2010 06:48, Che M wrote:

  I'm
using an SQLite3 database (with Python 2.5) and every so often the
application crashes or hangs because somewhere there is this error, or
something like it:

  

OperationalError:  database is locked.

  

This is probably because I am viewing and sometimes changing the
database through SQLite Database Browser while working on my app, and
occasionally the app tries to access the db when the Database Browser
is writing to it or something like that.    

  

I'd like to a) know how to reproduce the error (haven't seen it in a
while, but want to be sure  know when it may happen for users and b)
prevent it from being a problem in the running app.  

  

Any suggestions welcome.  Thank you,

Che

  

  Hotmail is redefining busy with tools for the New Busy. Get more
from your inbox. See how.
  
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
  



? SQLite is technically thread safe, but a write operation locks the
entire 

> database [1]:
> - Any resultset being step()'d through uses a shared read-only lock. 

> - Any insert/update being executed requires an exclusive write lock.





Thanks, that's fine to know, but what do I do in Python to address my concern?  



Che

 		 	   		  
_________________________________________________________________
The New Busy think 9 to 5 is a cute idea. Combine multiple calendars with Hotmail. 
http://www.windowslive.com/campaign/thenewbusy?tile=multicalendar&ocid=PID28326::T:WLMTAGL:ON:WL:en-US:WM_HMP:042010_5
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100721/526bb112/attachment.html>

From lang at tharin.com  Thu Jul 22 06:37:13 2010
From: lang at tharin.com (Lang Hurst)
Date: Wed, 21 Jul 2010 21:37:13 -0700
Subject: [Tutor] attachments?
In-Reply-To: <AANLkTilmTgNoqOwVlUi18IXRfjUc0KCpdKgyTbITN27h@mail.gmail.com>
References: <AANLkTilmTgNoqOwVlUi18IXRfjUc0KCpdKgyTbITN27h@mail.gmail.com>
Message-ID: <4C47CAF9.70608@tharin.com>

Naw, didn't come through.

On 07/21/2010 08:08 PM, Alex Hall wrote:

-- 
There are no stupid questions, just stupid people.


From amartin7211 at gmail.com  Thu Jul 22 06:48:22 2010
From: amartin7211 at gmail.com (Andrew Martin)
Date: Thu, 22 Jul 2010 00:48:22 -0400
Subject: [Tutor] Difficulty Understanding Example Code for Blender Script
Message-ID: <AANLkTinvCG_cafL0-95AIVyYjhDJxFgLsR1YIzPQ_E-Y@mail.gmail.com>

This code was part of a Blender script to build a 3d bar graph, so I don't
know if understanding Blender is a prereq for understanding this code. The
function is for the axis labels.

def label(text,position,orientation='z'):
    txt=Text3d.New('label')
    txt.setText(text)
    ob=Scene.GetCurrent().objects.new(txt)
    ob.setLocation(*position)
    if orientation=='x':
        ob.setEuler(-pi/2.0,0,0)
    elif orientation=='z':
        ob.setEuler(0,0,pi/2.0)
    print 'label %s at %s along %s' %(text,position,orientation)

 I understand it for the most part except for the orientation part. I assume
orientation is for the 3d text object, but how is it determined whether it
is x or z? Please keep replies simple; I am a newcomer to programming (and
if this makes no sense at all, I would appreciate polite inquiries for more
info).

Using Blender 2.49b and Python 2.6

Thanks a bunch,
amartin7211
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100722/c79c4846/attachment.html>

From marc.tompkins at gmail.com  Thu Jul 22 08:47:57 2010
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 21 Jul 2010 23:47:57 -0700
Subject: [Tutor] Difficulty Understanding Example Code for Blender Script
In-Reply-To: <AANLkTinvCG_cafL0-95AIVyYjhDJxFgLsR1YIzPQ_E-Y@mail.gmail.com>
References: <AANLkTinvCG_cafL0-95AIVyYjhDJxFgLsR1YIzPQ_E-Y@mail.gmail.com>
Message-ID: <AANLkTikFMFwP8zWUc9z7c1d--wq_8P4ImWuzMOf6qRyE@mail.gmail.com>

On Wed, Jul 21, 2010 at 9:48 PM, Andrew Martin <amartin7211 at gmail.com>wrote:

> This code was part of a Blender script to build a 3d bar graph, so I don't
> know if understanding Blender is a prereq for understanding this code. The
> function is for the axis labels.
>
> def label(text,position,orientation='z'):
>     txt=Text3d.New('label')
>     txt.setText(text)
>     ob=Scene.GetCurrent().objects.new(txt)
>     ob.setLocation(*position)
>     if orientation=='x':
>         ob.setEuler(-pi/2.0,0,0)
>     elif orientation=='z':
>         ob.setEuler(0,0,pi/2.0)
>     print 'label %s at %s along %s' %(text,position,orientation)
>
>  I understand it for the most part except for the orientation part. I
> assume orientation is for the 3d text object, but how is it determined
> whether it is x or z?


I don't use Blender myself, so this will be a more generic, high-level
answer...

> def label(text,position,orientation='z'):
>
This definition specifies that label() takes two mandatory parameters - text
and position - and one optional parameter, orientation.  What makes
"orientation" optional is the fact that a default value is supplied:
"orientation='z'".  In other words, "orientation" is equal to "z" unless you
specify otherwise in your call to label().

Take a look at this section of the Python docs:
http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions

Hope that helps...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100721/b69d4aad/attachment.html>

From smokefloat at gmail.com  Thu Jul 22 09:06:52 2010
From: smokefloat at gmail.com (David Hutto)
Date: Thu, 22 Jul 2010 03:06:52 -0400
Subject: [Tutor] Difficulty Understanding Example Code for Blender Script
In-Reply-To: <AANLkTikFMFwP8zWUc9z7c1d--wq_8P4ImWuzMOf6qRyE@mail.gmail.com>
References: <AANLkTinvCG_cafL0-95AIVyYjhDJxFgLsR1YIzPQ_E-Y@mail.gmail.com>
	<AANLkTikFMFwP8zWUc9z7c1d--wq_8P4ImWuzMOf6qRyE@mail.gmail.com>
Message-ID: <AANLkTikW3nD9CosnnLSKNhpskXRjKVNNFmWsGkSRURqB@mail.gmail.com>

On Thu, Jul 22, 2010 at 2:47 AM, Marc Tompkins <marc.tompkins at gmail.com> wrote:
> On Wed, Jul 21, 2010 at 9:48 PM, Andrew Martin <amartin7211 at gmail.com>
> wrote:
>>
>> This code was part of a Blender script to build a 3d bar graph, so I don't
>> know if understanding Blender is a prereq for understanding this code. The
>> function is for the axis labels.
>>
>> def label(text,position,orientation='z'):
>> ??? txt=Text3d.New('label')
>> ??? txt.setText(text)
>> ??? ob=Scene.GetCurrent().objects.new(txt)
>> ??? ob.setLocation(*position)
>> ??? if orientation=='x':
>> ??? ??? ob.setEuler(-pi/2.0,0,0)
>> ??? elif orientation=='z':
>> ??? ??? ob.setEuler(0,0,pi/2.0)
>> ??? print 'label %s at %s along %s' %(text,position,orientation)
>>
>> ?I understand it for the most part except for the orientation part. I
>> assume orientation is for the 3d text object, but how is it determined
>> whether it is x or z?
>
> I don't use Blender myself, so this will be a more generic, high-level
> answer...
>>
>> def label(text,position,orientation='z'):
>
> This definition specifies that label() takes two mandatory parameters - text
> and position - and one optional parameter, orientation.? What makes
> "orientation" optional is the fact that a default value is supplied:
> "orientation='z'".? In other words, "orientation" is equal to "z" unless you
> specify otherwise in your call to label().

Seeing as how blender is 3d graphics, have you tried the 'newbie
fidget with it', and typed in w(quaternion),x, or y to see what
occurs. Also, have you looked into the hierarchy to see if z, which
looks as though it's contained in a string, is an input variable
declared elsewhere as an integer, or represents something else in it's
usage. Z can mean global, or object orientation in blender from what I
see.

>
> Take a look at this section of the Python docs:
> http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions
>
> Hope that helps...
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

From mehgcap at gmail.com  Thu Jul 22 15:30:14 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Thu, 22 Jul 2010 09:30:14 -0400
Subject: [Tutor] "expected an indented block" (see attached)
Message-ID: <AANLkTin8-rmeUrg1FjTeC6Iy3Dbm5qN7CIE-GcqwIGiF@mail.gmail.com>

Hi all,
Attached is a file. When I run the program it is part of, I get an
error that says:
line 62: IndentationError: expected an indented block.

I can see nothing wrong with the indentation, though. This is part of
my Battleship game, defining all the different ships and aircraft the
user can have, as well as the special weapons methods for each ship.
If anyone can spot the problem, it would be great. I know I only
indent one space, instead of the normal four, but I use a screen
reader and it is a lot easier and faster to do it this way. If a
version of Python based on braces instead of indents were released, my
world would be so much better!

-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap
-------------- next part --------------
A non-text attachment was scrubbed...
Name: craft.py
Type: application/octet-stream
Size: 5061 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100722/043fe8e8/attachment.obj>

From evert.rol at gmail.com  Thu Jul 22 15:35:43 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 22 Jul 2010 15:35:43 +0200
Subject: [Tutor] "expected an indented block" (see attached)
In-Reply-To: <AANLkTin8-rmeUrg1FjTeC6Iy3Dbm5qN7CIE-GcqwIGiF@mail.gmail.com>
References: <AANLkTin8-rmeUrg1FjTeC6Iy3Dbm5qN7CIE-GcqwIGiF@mail.gmail.com>
Message-ID: <0F1C805F-B16A-4071-9AD9-8CD48C32A3B2@gmail.com>

> Attached is a file. When I run the program it is part of, I get an
> error that says:
> line 62: IndentationError: expected an indented block.

This function:

 def fromString(self, str):
  #creates a Craft object from the string
#end class Craft


Is completely empty (the comment lines are discarded). So Python expects any next piece of code to be inside this method (and thus indented).
If you want an empty function, use 'pass' instead.

(also consider using four spaces for indentation, which I've also found much clearer. Have a read through PEP 8; has a lot of interesting tidbits. 
And an editor with a good Python mode is very handy, because that would have almost automatically indented the next piece of code, 'class Battleship(Craft)', which would have indicated something went awry before that line).



> I can see nothing wrong with the indentation, though. This is part of
> my Battleship game, defining all the different ships and aircraft the
> user can have, as well as the special weapons methods for each ship.
> If anyone can spot the problem, it would be great. I know I only
> indent one space, instead of the normal four, but I use a screen
> reader and it is a lot easier and faster to do it this way. If a
> version of Python based on braces instead of indents were released, my
> world would be so much better!


From mehgcap at gmail.com  Thu Jul 22 15:52:53 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Thu, 22 Jul 2010 09:52:53 -0400
Subject: [Tutor] "expected an indented block" (see attached)
In-Reply-To: <0F1C805F-B16A-4071-9AD9-8CD48C32A3B2@gmail.com>
References: <AANLkTin8-rmeUrg1FjTeC6Iy3Dbm5qN7CIE-GcqwIGiF@mail.gmail.com>
	<0F1C805F-B16A-4071-9AD9-8CD48C32A3B2@gmail.com>
Message-ID: <AANLkTinx2VfnM43WBcrIN521Ro1RABHkeFW7YCD5tekF@mail.gmail.com>

On 7/22/10, Evert Rol <evert.rol at gmail.com> wrote:
>> Attached is a file. When I run the program it is part of, I get an
>> error that says:
>> line 62: IndentationError: expected an indented block.
>
> This function:
>
>  def fromString(self, str):
>   #creates a Craft object from the string
> #end class Craft
>
>
> Is completely empty (the comment lines are discarded). So Python expects any
> next piece of code to be inside this method (and thus indented).
Oh, I did not realize it threw out comments. That explains it, then!
> If you want an empty function, use 'pass' instead.
>
> (also consider using four spaces for indentation, which I've also found much
> clearer. Have a read through PEP 8; has a lot of interesting tidbits.
> And an editor with a good Python mode is very handy, because that would have
> almost automatically indented the next piece of code, 'class
> Battleship(Craft)', which would have indicated something went awry before
> that line).
The only problem is that I have not found an accessible editor that
will do this.
>
>
>
>> I can see nothing wrong with the indentation, though. This is part of
>> my Battleship game, defining all the different ships and aircraft the
>> user can have, as well as the special weapons methods for each ship.
>> If anyone can spot the problem, it would be great. I know I only
>> indent one space, instead of the normal four, but I use a screen
>> reader and it is a lot easier and faster to do it this way. If a
>> version of Python based on braces instead of indents were released, my
>> world would be so much better!
>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From hugo.yoshi at gmail.com  Thu Jul 22 16:13:35 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Thu, 22 Jul 2010 16:13:35 +0200
Subject: [Tutor] "expected an indented block" (see attached)
In-Reply-To: <0F1C805F-B16A-4071-9AD9-8CD48C32A3B2@gmail.com>
References: <AANLkTin8-rmeUrg1FjTeC6Iy3Dbm5qN7CIE-GcqwIGiF@mail.gmail.com> 
	<0F1C805F-B16A-4071-9AD9-8CD48C32A3B2@gmail.com>
Message-ID: <AANLkTikAuxKLx8TNX-WF-P0A51AnkONS46X_WnJQy6Xz@mail.gmail.com>

On Thu, Jul 22, 2010 at 3:35 PM, Evert Rol <evert.rol at gmail.com> wrote:
>> Attached is a file. When I run the program it is part of, I get an
>> error that says:
>> line 62: IndentationError: expected an indented block.
>
> This function:
>
> ?def fromString(self, str):
> ?#creates a Craft object from the string
> #end class Craft
>
>
> Is completely empty (the comment lines are discarded). So Python expects any next piece of code to be inside this method (and thus indented).
> If you want an empty function, use 'pass' instead.
>
> (also consider using four spaces for indentation, which I've also found much clearer. Have a read through PEP 8; has a lot of interesting tidbits.

Did you read the rest of his post? He's using a screen reader for a
reason; he can't *see* the code. visual means of structuring code like
whitespace are meaningless to him at best, and annoying at worst. No
wonder his code is littered with '#end def' comments. Python's
significant indentation is horrible for the blind, at least until we
create a more specialized/better screen reader.

Alex, Perhaps a better solution is to indent with tabs rather than
spaces, though I'm normally opposed to using tabs. Alternatively, run
your files through a script that expands every indent space to four
spaces before posting here. I've attached a bare-bones script that
takes a file and a number as argument, replaces every initial space
with that number of spaces, and writes the result to a new file
(filename is just the old filename with .new appended).

Yes, the script is indented with four spaces, Sorry. I'm sure you
could write a script that does the reverse operation so it becomes a
little more readable for you.

Hugo
-------------- next part --------------
A non-text attachment was scrubbed...
Name: indent.py
Type: text/x-python
Size: 551 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100722/4c4409f9/attachment-0001.py>

From evert.rol at gmail.com  Thu Jul 22 16:17:25 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 22 Jul 2010 16:17:25 +0200
Subject: [Tutor] "expected an indented block" (see attached)
In-Reply-To: <AANLkTikAuxKLx8TNX-WF-P0A51AnkONS46X_WnJQy6Xz@mail.gmail.com>
References: <AANLkTin8-rmeUrg1FjTeC6Iy3Dbm5qN7CIE-GcqwIGiF@mail.gmail.com>
	<0F1C805F-B16A-4071-9AD9-8CD48C32A3B2@gmail.com>
	<AANLkTikAuxKLx8TNX-WF-P0A51AnkONS46X_WnJQy6Xz@mail.gmail.com>
Message-ID: <0F2F8E1E-411A-43F9-BFB8-72B4AA7A0E4B@gmail.com>

>> (also consider using four spaces for indentation, which I've also found much clearer. Have a read through PEP 8; has a lot of interesting tidbits.
> 
> Did you read the rest of his post? He's using a screen reader for a
> reason; he can't *see* the code. visual means of structuring code like
> whitespace are meaningless to him at best, and annoying at worst. No
> wonder his code is littered with '#end def' comments. Python's
> significant indentation is horrible for the blind, at least until we
> create a more specialized/better screen reader.

Sorry, I had obviously missed that. Apologies. 



From mehgcap at gmail.com  Thu Jul 22 16:24:14 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Thu, 22 Jul 2010 10:24:14 -0400
Subject: [Tutor] "expected an indented block" (see attached)
In-Reply-To: <AANLkTikAuxKLx8TNX-WF-P0A51AnkONS46X_WnJQy6Xz@mail.gmail.com>
References: <AANLkTin8-rmeUrg1FjTeC6Iy3Dbm5qN7CIE-GcqwIGiF@mail.gmail.com>
	<0F1C805F-B16A-4071-9AD9-8CD48C32A3B2@gmail.com>
	<AANLkTikAuxKLx8TNX-WF-P0A51AnkONS46X_WnJQy6Xz@mail.gmail.com>
Message-ID: <AANLkTikB9iG8xE0uv9re_yRwNXoNXgW-en5vPdMlOowf@mail.gmail.com>

On 7/22/10, Hugo Arts <hugo.yoshi at gmail.com> wrote:
> On Thu, Jul 22, 2010 at 3:35 PM, Evert Rol <evert.rol at gmail.com> wrote:
>>> Attached is a file. When I run the program it is part of, I get an
>>> error that says:
>>> line 62: IndentationError: expected an indented block.
>>
>> This function:
>>
>>  def fromString(self, str):
>>  #creates a Craft object from the string
>> #end class Craft
>>
>>
>> Is completely empty (the comment lines are discarded). So Python expects
>> any next piece of code to be inside this method (and thus indented).
>> If you want an empty function, use 'pass' instead.
>>
>> (also consider using four spaces for indentation, which I've also found
>> much clearer. Have a read through PEP 8; has a lot of interesting tidbits.
>
> Did you read the rest of his post? He's using a screen reader for a
> reason; he can't *see* the code. visual means of structuring code like
> whitespace are meaningless to him at best, and annoying at worst. No
> wonder his code is littered with '#end def' comments. Python's
> significant indentation is horrible for the blind, at least until we
> create a more specialized/better screen reader.
I think a specialized editor is all it would take. Edsharp
(http://www.empowermentzone.com/edsetup.exe) has a way of converting
braced code into Pythonic indents and colons, but you then have to
manage two sets of files, the braced code and the indented code.
Perhaps such an editor is a future project for me...
>
> Alex, Perhaps a better solution is to indent with tabs rather than
> spaces, though I'm normally opposed to using tabs. Alternatively, run
> your files through a script that expands every indent space to four
> spaces before posting here. I've attached a bare-bones script that
> takes a file and a number as argument, replaces every initial space
> with that number of spaces, and writes the result to a new file
> (filename is just the old filename with .new appended).
Tabs are worse because, for some very annoying reason, my reader reads
both hard returns and tabs as the word "blank". That means that I have
no way of knowing when I am reading a tab and when I have gone to a
previous line. Spaces are the only viable option.
Thanks for the script; if I have to attach code in the future, I will
try to remember to run the file(s) through it for easier reading. I
can also make your script remove the #end... comments, since I know a
lot of people do not like them either.
>
> Yes, the script is indented with four spaces, Sorry. I'm sure you
> could write a script that does the reverse operation so it becomes a
> little more readable for you.
>
> Hugo
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From waynejwerner at gmail.com  Thu Jul 22 16:38:33 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Thu, 22 Jul 2010 09:38:33 -0500
Subject: [Tutor] "expected an indented block" (see attached)
In-Reply-To: <AANLkTikB9iG8xE0uv9re_yRwNXoNXgW-en5vPdMlOowf@mail.gmail.com>
References: <AANLkTin8-rmeUrg1FjTeC6Iy3Dbm5qN7CIE-GcqwIGiF@mail.gmail.com> 
	<0F1C805F-B16A-4071-9AD9-8CD48C32A3B2@gmail.com>
	<AANLkTikAuxKLx8TNX-WF-P0A51AnkONS46X_WnJQy6Xz@mail.gmail.com> 
	<AANLkTikB9iG8xE0uv9re_yRwNXoNXgW-en5vPdMlOowf@mail.gmail.com>
Message-ID: <AANLkTil8JbI2fbaQ5cY6NkqmoGatte02rOlNUoufnw6B@mail.gmail.com>

On Thu, Jul 22, 2010 at 9:24 AM, Alex Hall <mehgcap at gmail.com> wrote:

> <snip> Edsharp
> (http://www.empowermentzone.com/edsetup.exe) has a way of converting
> braced code into Pythonic indents and colons, but you then have to
> manage two sets of files, the braced code and the indented code.
> Perhaps such an editor is a future project for me...


I bet there are many (or at least a few) willing to work on an Open Source
project like this. I know I'd be willing to throw some time and talents at
helping create a Python editor or some conversion tools for the
blind/visually impared.

-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100722/85992549/attachment.html>

From hugo.yoshi at gmail.com  Thu Jul 22 16:57:46 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Thu, 22 Jul 2010 16:57:46 +0200
Subject: [Tutor] "expected an indented block" (see attached)
In-Reply-To: <AANLkTil8JbI2fbaQ5cY6NkqmoGatte02rOlNUoufnw6B@mail.gmail.com>
References: <AANLkTin8-rmeUrg1FjTeC6Iy3Dbm5qN7CIE-GcqwIGiF@mail.gmail.com> 
	<0F1C805F-B16A-4071-9AD9-8CD48C32A3B2@gmail.com>
	<AANLkTikAuxKLx8TNX-WF-P0A51AnkONS46X_WnJQy6Xz@mail.gmail.com> 
	<AANLkTikB9iG8xE0uv9re_yRwNXoNXgW-en5vPdMlOowf@mail.gmail.com> 
	<AANLkTil8JbI2fbaQ5cY6NkqmoGatte02rOlNUoufnw6B@mail.gmail.com>
Message-ID: <AANLkTimGVR-Ehi0EXdussSnhLW5q5iWbl1mbE4SJ2O-t@mail.gmail.com>

On Thu, Jul 22, 2010 at 4:38 PM, Wayne Werner <waynejwerner at gmail.com> wrote:
> On Thu, Jul 22, 2010 at 9:24 AM, Alex Hall <mehgcap at gmail.com> wrote:
>>
>> <snip> Edsharp
>> (http://www.empowermentzone.com/edsetup.exe) has a way of converting
>> braced code into Pythonic indents and colons, but you then have to
>> manage two sets of files, the braced code and the indented code.
>> Perhaps such an editor is a future project for me...
>
> I bet there are many (or at least a few) willing to work on an Open Source
> project like this. I know I'd be willing to throw some time and talents at
> helping create a Python editor or some conversion tools for the
> blind/visually impared.
> -Wayne

++, this sounds like a worthwhile project.

From lie.1296 at gmail.com  Thu Jul 22 17:41:59 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Thu, 22 Jul 2010 15:41:59 -0000
Subject: [Tutor] "x and y" means "if x is false, then x, else y"??
In-Reply-To: <AANLkTilaAD-8T27wCswUim3EtY4r30yP2HmjeyuZNxQl@mail.gmail.com>
References: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com>
	<4C318FF0.8020602@alchemy.com>	<AANLkTimxON5RbEPCSkHnrPvwItqwtV0YNegZxFGrqNvY@mail.gmail.com>
	<i0sehe$9j1$1@dough.gmane.org>	<AANLkTilh7dSrItv-pxDASPV9DkpHSjWx_c0Dwr0MPHQl@mail.gmail.com>
	<AANLkTimM8QQ9LxPhHwveFHt0LlxDLsGaeTrlkdFdw4m9@mail.gmail.com>
	<AANLkTilaAD-8T27wCswUim3EtY4r30yP2HmjeyuZNxQl@mail.gmail.com>
Message-ID: <i29orr$n7u$1@dough.gmane.org>

On 07/05/10 22:23, Adam Bark wrote:

> 
> I should add that this is how something like:
> 
> if x != y:
>     do_something()
> 
> works, if expects a True or False (this isn't always true but works for
> comparison operators expressions such as this).
> 

<nit> "if" expects an expression that can be converted to True or False
by calling its __bool__()/__nonzero__(); in case of missing
__bool__/__nonzero__, then the object is considered True. </nit>


From adam.jtm30 at gmail.com  Thu Jul 22 18:33:39 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Thu, 22 Jul 2010 17:33:39 +0100
Subject: [Tutor] "x and y" means "if x is false, then x, else y"??
In-Reply-To: <i29orr$n7u$1@dough.gmane.org>
References: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com> 
	<4C318FF0.8020602@alchemy.com>
	<AANLkTimxON5RbEPCSkHnrPvwItqwtV0YNegZxFGrqNvY@mail.gmail.com> 
	<i0sehe$9j1$1@dough.gmane.org>
	<AANLkTilh7dSrItv-pxDASPV9DkpHSjWx_c0Dwr0MPHQl@mail.gmail.com> 
	<AANLkTimM8QQ9LxPhHwveFHt0LlxDLsGaeTrlkdFdw4m9@mail.gmail.com> 
	<AANLkTilaAD-8T27wCswUim3EtY4r30yP2HmjeyuZNxQl@mail.gmail.com> 
	<i29orr$n7u$1@dough.gmane.org>
Message-ID: <AANLkTimDScYeAz015jhzUmcwVnSlA1xulEwoS_YWL3E5@mail.gmail.com>

On 6 July 2010 02:05, Lie Ryan <lie.1296 at gmail.com> wrote:

> On 07/05/10 22:23, Adam Bark wrote:
>
> >
> > I should add that this is how something like:
> >
> > if x != y:
> >     do_something()
> >
> > works, if expects a True or False (this isn't always true but works for
> > comparison operators expressions such as this).
> >
>
> <nit> "if" expects an expression that can be converted to True or False
> by calling its __bool__()/__nonzero__(); in case of missing
> __bool__/__nonzero__, then the object is considered True. </nit>
>
>
Well put, I couldn't decide how to phrase it without adding confusion but
you hit the nail on the head.
Cheers,
Adam.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100722/c8ededd2/attachment-0001.html>

From __peter__ at web.de  Thu Jul 22 19:42:20 2010
From: __peter__ at web.de (Peter Otten)
Date: Thu, 22 Jul 2010 19:42:20 +0200
Subject: [Tutor] "x and y" means "if x is false, then x, else y"??
References: <AANLkTil7OnvufYP8-xv8uks0amIsrni5hBGMvDqoj9ui@mail.gmail.com>
	<4C318FF0.8020602@alchemy.com>
	<AANLkTimxON5RbEPCSkHnrPvwItqwtV0YNegZxFGrqNvY@mail.gmail.com>
	<i0sehe$9j1$1@dough.gmane.org>
	<AANLkTilh7dSrItv-pxDASPV9DkpHSjWx_c0Dwr0MPHQl@mail.gmail.com>
	<AANLkTimM8QQ9LxPhHwveFHt0LlxDLsGaeTrlkdFdw4m9@mail.gmail.com>
	<AANLkTilaAD-8T27wCswUim3EtY4r30yP2HmjeyuZNxQl@mail.gmail.com>
	<i29orr$n7u$1@dough.gmane.org>
Message-ID: <i29vt5$i65$1@dough.gmane.org>

Lie Ryan wrote:

> On 07/05/10 22:23, Adam Bark wrote:
> 
>> 
>> I should add that this is how something like:
>> 
>> if x != y:
>>     do_something()
>> 
>> works, if expects a True or False (this isn't always true but works for
>> comparison operators expressions such as this).
>> 
> 
> <nit> "if" expects an expression that can be converted to True or False
> by calling its __bool__()/__nonzero__(); in case of missing
> __bool__/__nonzero__, then the object is considered True. </nit>

<meta:nit>Don't forget about __len__()</meta:nit>

>>> class A:
...     def __init__(self, n): self.n = n
...     def __len__(self): return self.n
...
>>> "yes" if A(1) else "no"
'yes'
>>> "yes" if A(0) else "no"
'no'

Bonus:

>>> "yes" if A(-1) else "no"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: __nonzero__ should return >= 0

Peter


From mehgcap at gmail.com  Fri Jul 23 01:49:24 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Thu, 22 Jul 2010 19:49:24 -0400
Subject: [Tutor] sound libraries?
Message-ID: <AANLkTikXgtC8x_mvoxk9PDFNCVwv4ZrRpi_a2My8RvRc@mail.gmail.com>

Hi all,
I am curious. If I wanted a library that would let me play sounds at
specific positions in the stereo field, then update that position as
the user "moved" so that it would seem to be a fixed reference point,
what would I use? For example, say the left/right arrows move you left
and right. In the center of your stereo field you hear a sound, say a
bell. As you press the arrow keys, the sound moves, or rather, you
move but the sound stays the same. Pysonic looks like the perfect
answer, but it seems to require python2.3, and I am using 2.6. Are
there any other conprehensive sound libraries that would allow for
dynamic positioning of sound, doplar effects, volume control, and so
on?

-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From coolankur2006 at gmail.com  Fri Jul 23 01:51:37 2010
From: coolankur2006 at gmail.com (ANKUR AGGARWAL)
Date: Fri, 23 Jul 2010 05:21:37 +0530
Subject: [Tutor] how i can change two lists into one directory
Message-ID: <AANLkTin6KiA8cbvaFirpSFfRXE=MkVoUrexJUORmeh4+@mail.gmail.com>

hey i have just started making  a app using python and just gt a problem..

i have two list
a=["x","z"]
b=[1,2]

i want to make a directory like this
c={"x":1,"z":2}

is it possible???? i mean i tried it using loops and all but i cant append a
directory so i m unable to do this...
plz tell me if there's any way to get the directory like this.... Thanks in
advance :):)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100723/26184a59/attachment.html>

From coolankur2006 at gmail.com  Fri Jul 23 01:47:05 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:05 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234705.GA4471@ankur-laptop>


From mehgcap at gmail.com  Fri Jul 23 02:06:10 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Thu, 22 Jul 2010 20:06:10 -0400
Subject: [Tutor] (no subject)
In-Reply-To: <20100722234705.GA4471@ankur-laptop>
References: <20100722234705.GA4471@ankur-laptop>
Message-ID: <AANLkTim1nPcn_tPuEl8V_AnsExm1KIgXd9GYFQKZYDFT@mail.gmail.com>

This message was blank, I am not sure if that was the idea or not.

On 7/22/10, ankur <coolankur2006 at gmail.com> wrote:
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From coolankur2006 at gmail.com  Fri Jul 23 01:46:20 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:16:20 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234620.GA3971@ankur-laptop>


From mehgcap at gmail.com  Fri Jul 23 02:08:53 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Thu, 22 Jul 2010 20:08:53 -0400
Subject: [Tutor] how i can change two lists into one directory
In-Reply-To: <AANLkTin6KiA8cbvaFirpSFfRXE=MkVoUrexJUORmeh4+@mail.gmail.com>
References: <AANLkTin6KiA8cbvaFirpSFfRXE=MkVoUrexJUORmeh4+@mail.gmail.com>
Message-ID: <AANLkTik7X2v8ajOoDB7lnz7rbrMT4bLDQic6zl9qVFZv@mail.gmail.com>

On 7/22/10, ANKUR AGGARWAL <coolankur2006 at gmail.com> wrote:
> hey i have just started making  a app using python and just gt a problem..
>
> i have two list
> a=["x","z"]
> b=[1,2]
>
> i want to make a directory like this
It is called a dictionary, actually.
> c={"x":1,"z":2}
>
> is it possible???? i mean i tried it using loops and all but i cant append a
> directory so i m unable to do this...
> plz tell me if there's any way to get the directory like this.... Thanks in
> advance :):)
idx=0
for i in a:
    c[i]=b[idx]
    idx+=1
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From coolankur2006 at gmail.com  Fri Jul 23 01:47:05 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:05 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234705.GA4457@ankur-laptop>


From coolankur2006 at gmail.com  Fri Jul 23 01:47:03 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:03 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234703.GA4348@ankur-laptop>


From coolankur2006 at gmail.com  Fri Jul 23 01:47:03 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:03 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234703.GA4410@ankur-laptop>


From coolankur2006 at gmail.com  Fri Jul 23 01:47:03 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:03 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234703.GA4390@ankur-laptop>


From coolankur2006 at gmail.com  Fri Jul 23 01:47:03 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:03 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234703.GA4376@ankur-laptop>


From coolankur2006 at gmail.com  Fri Jul 23 01:46:16 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:16:16 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234616.GA3927@ankur-laptop>


From coolankur2006 at gmail.com  Fri Jul 23 01:47:01 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:01 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234701.GA4250@ankur-laptop>


From coolankur2006 at gmail.com  Fri Jul 23 01:47:02 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:02 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234702.GA4289@ankur-laptop>


From coolankur2006 at gmail.com  Fri Jul 23 01:47:02 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:02 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234701.GA4275@ankur-laptop>


From coolankur2006 at gmail.com  Fri Jul 23 01:47:05 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:05 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234705.GA4443@ankur-laptop>


From coolankur2006 at gmail.com  Fri Jul 23 01:47:04 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:04 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234704.GA4429@ankur-laptop>


From bgailer at gmail.com  Fri Jul 23 02:15:37 2010
From: bgailer at gmail.com (bob gailer)
Date: Thu, 22 Jul 2010 20:15:37 -0400
Subject: [Tutor] how i can change two lists into one directory
In-Reply-To: <AANLkTin6KiA8cbvaFirpSFfRXE=MkVoUrexJUORmeh4+@mail.gmail.com>
References: <AANLkTin6KiA8cbvaFirpSFfRXE=MkVoUrexJUORmeh4+@mail.gmail.com>
Message-ID: <4C48DF29.1070808@gmail.com>

On 7/22/2010 7:51 PM, ANKUR AGGARWAL wrote:
> hey i have just started making  a app using python and just gt a 
> problem..
>
> i have two list
> a=["x","z"]
> b=[1,2]
>
> i want to make a directory like this

Do you mean "dictionary"?

> c={"x":1,"z":2}
>
> is it possible????

Indeed. There are several ways to do this. Easiest:

dict(zip(a,b))

> i mean i tried it using loops

d = {}
for i in range(len(a)):
   d[a[i] = b[i]

> and all but i cant append a directory

Of course you can't append, since a dictionary is not a sequence. But 
you can add a key-value pair as the above loop demonstrates.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From coolankur2006 at gmail.com  Fri Jul 23 01:47:03 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:03 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234703.GA4362@ankur-laptop>


From coolankur2006 at gmail.com  Fri Jul 23 01:47:02 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:02 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234702.GA4303@ankur-laptop>


From coolankur2006 at gmail.com  Fri Jul 23 01:47:02 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:02 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234702.GA4317@ankur-laptop>


From coolankur2006 at gmail.com  Fri Jul 23 01:47:02 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:02 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234702.GA4331@ankur-laptop>


From coolankur2006 at gmail.com  Fri Jul 23 01:47:01 2010
From: coolankur2006 at gmail.com (ankur)
Date: Fri, 23 Jul 2010 05:17:01 +0530
Subject: [Tutor] (no subject)
Message-ID: <20100722234701.GA4236@ankur-laptop>


From steve at pearwood.info  Fri Jul 23 02:37:44 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 23 Jul 2010 10:37:44 +1000
Subject: [Tutor] how i can change two lists into one directory
In-Reply-To: <AANLkTin6KiA8cbvaFirpSFfRXE=MkVoUrexJUORmeh4+@mail.gmail.com>
References: <AANLkTin6KiA8cbvaFirpSFfRXE=MkVoUrexJUORmeh4+@mail.gmail.com>
Message-ID: <201007231037.45345.steve@pearwood.info>

On Fri, 23 Jul 2010 09:51:37 am ANKUR AGGARWAL wrote:
> hey i have just started making  a app using python and just gt a
> problem..
>
> i have two list
> a=["x","z"]
> b=[1,2]
>
> i want to make a directory like this
> c={"x":1,"z":2}


The word you want is "dictionary" or "dict", not directory.

Here's one slow, boring, manual way:

a = ["x", "z"]
b = [1, 2]
c = {}
c[a[0]] = b[0]
c[a[1]] = b[1]

You can turn that into a loop:

c = {}
for index in range( min(len(a), len(b)) ):
    c[a[i]] = b[i]


Here's the sensible way that makes Python do all the heavy lifting:

c = dict(zip(a, b))



-- 
Steven D'Aprano

From rabidpoobear at gmail.com  Fri Jul 23 03:05:59 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 22 Jul 2010 20:05:59 -0500
Subject: [Tutor] sound libraries?
In-Reply-To: <AANLkTikXgtC8x_mvoxk9PDFNCVwv4ZrRpi_a2My8RvRc@mail.gmail.com>
References: <AANLkTikXgtC8x_mvoxk9PDFNCVwv4ZrRpi_a2My8RvRc@mail.gmail.com>
Message-ID: <A25CFBE4-E132-405B-9879-69E7310AD4D3@gmail.com>

You can access openal through either pyglet or pygame I believe, and definitely thru panda3d. That would allow you to have true 3d sound positioning and I believe openal can automatically Doppler too, not sure though. Let us know what you go with or if you have questions.

Sent from my iPhone

On Jul 22, 2010, at 6:49 PM, Alex Hall <mehgcap at gmail.com> wrote:

> Hi all,
> I am curious. If I wanted a library that would let me play sounds at
> specific positions in the stereo field, then update that position as
> the user "moved" so that it would seem to be a fixed reference point,
> what would I use? For example, say the left/right arrows move you left
> and right. In the center of your stereo field you hear a sound, say a
> bell. As you press the arrow keys, the sound moves, or rather, you
> move but the sound stays the same. Pysonic looks like the perfect
> answer, but it seems to require python2.3, and I am using 2.6. Are
> there any other conprehensive sound libraries that would allow for
> dynamic positioning of sound, doplar effects, volume control, and so
> on?
> 
> -- 
> Have a great day,
> Alex (msg sent from GMail website)
> mehgcap at gmail.com; http://www.facebook.com/mehgcap
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From rabidpoobear at gmail.com  Fri Jul 23 03:06:57 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 22 Jul 2010 20:06:57 -0500
Subject: [Tutor] how i can change two lists into one directory
In-Reply-To: <AANLkTik7X2v8ajOoDB7lnz7rbrMT4bLDQic6zl9qVFZv@mail.gmail.com>
References: <AANLkTin6KiA8cbvaFirpSFfRXE=MkVoUrexJUORmeh4+@mail.gmail.com>
	<AANLkTik7X2v8ajOoDB7lnz7rbrMT4bLDQic6zl9qVFZv@mail.gmail.com>
Message-ID: <8F978CC0-7954-488D-8E32-8BDC7B5EB132@gmail.com>

Hey quit spamming the list please.

Sent from my iPhone

On Jul 22, 2010, at 7:08 PM, Alex Hall <mehgcap at gmail.com> wrote:

> On 7/22/10, ANKUR AGGARWAL <coolankur2006 at gmail.com> wrote:
>> hey i have just started making  a app using python and just gt a problem..
>> 
>> i have two list
>> a=["x","z"]
>> b=[1,2]
>> 
>> i want to make a directory like this
> It is called a dictionary, actually.
>> c={"x":1,"z":2}
>> 
>> is it possible???? i mean i tried it using loops and all but i cant append a
>> directory so i m unable to do this...
>> plz tell me if there's any way to get the directory like this.... Thanks in
>> advance :):)
> idx=0
> for i in a:
>    c[i]=b[idx]
>    idx+=1
>> 
> 
> 
> -- 
> Have a great day,
> Alex (msg sent from GMail website)
> mehgcap at gmail.com; http://www.facebook.com/mehgcap
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From mehgcap at gmail.com  Fri Jul 23 03:27:20 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Thu, 22 Jul 2010 21:27:20 -0400
Subject: [Tutor] sound libraries?
In-Reply-To: <A25CFBE4-E132-405B-9879-69E7310AD4D3@gmail.com>
References: <AANLkTikXgtC8x_mvoxk9PDFNCVwv4ZrRpi_a2My8RvRc@mail.gmail.com>
	<A25CFBE4-E132-405B-9879-69E7310AD4D3@gmail.com>
Message-ID: <AANLkTikav3CoHHo66vIsPNzv9T4LMJO2plbGjJDCniLJ@mail.gmail.com>

On 7/22/10, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> You can access openal through either pyglet or pygame I believe, and
> definitely thru panda3d. That would allow you to have true 3d sound
> positioning and I believe openal can automatically Doppler too, not sure
> though. Let us know what you go with or if you have questions.
Thanks. I have pygame but was less than impressed with its audio
features, though it is quite possible that I missed or misread
something. I am downloading Panda3d right now; its audio documentation
looks quite promising. Looks like doplaring is supported, too.
>
> Sent from my iPhone
>
> On Jul 22, 2010, at 6:49 PM, Alex Hall <mehgcap at gmail.com> wrote:
>
>> Hi all,
>> I am curious. If I wanted a library that would let me play sounds at
>> specific positions in the stereo field, then update that position as
>> the user "moved" so that it would seem to be a fixed reference point,
>> what would I use? For example, say the left/right arrows move you left
>> and right. In the center of your stereo field you hear a sound, say a
>> bell. As you press the arrow keys, the sound moves, or rather, you
>> move but the sound stays the same. Pysonic looks like the perfect
>> answer, but it seems to require python2.3, and I am using 2.6. Are
>> there any other conprehensive sound libraries that would allow for
>> dynamic positioning of sound, doplar effects, volume control, and so
>> on?
>>
>> --
>> Have a great day,
>> Alex (msg sent from GMail website)
>> mehgcap at gmail.com; http://www.facebook.com/mehgcap
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From webtourist at gmail.com  Fri Jul 23 04:31:52 2010
From: webtourist at gmail.com (Robert)
Date: Thu, 22 Jul 2010 22:31:52 -0400
Subject: [Tutor] how i can change two lists into one directory
In-Reply-To: <8F978CC0-7954-488D-8E32-8BDC7B5EB132@gmail.com>
References: <AANLkTin6KiA8cbvaFirpSFfRXE=MkVoUrexJUORmeh4+@mail.gmail.com> 
	<AANLkTik7X2v8ajOoDB7lnz7rbrMT4bLDQic6zl9qVFZv@mail.gmail.com> 
	<8F978CC0-7954-488D-8E32-8BDC7B5EB132@gmail.com>
Message-ID: <AANLkTimeCKXEhGPivJDf329A7n3pN0XHKgHRsof1RdQR@mail.gmail.com>

looks like this guy figured out how to send email in a loop

From mhw at doctors.net.uk  Fri Jul 23 13:22:55 2010
From: mhw at doctors.net.uk (mhw at doctors.net.uk)
Date: Fri, 23 Jul 2010 11:22:55 +0000
Subject: [Tutor] Implementing sets of user-defined objects
Message-ID: <2009502226-1279884215-cardhu_decombobulator_blackberry.rim.net-639053653-@bda188.bisx.produk.on.blackberry>

Dear Tutors,

I am tring to deal with some repeated data, and hence repeated objects (I construct objects from the data).

I had hoped to use a set to uniquify the objects. However, I am having problems with defining uniqueness.

I have googled/ looked at the Python docs/ read DITP and Alan's website, but I'm still not clear how the set() determines object uniqueness. There seem to be some references to __cmp__() and __eq__(), but I'm not clear what I should be using.

Any pointers very welcome.

Matt
Sent from my BlackBerry? wireless device

From steve at pearwood.info  Fri Jul 23 14:57:56 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 23 Jul 2010 22:57:56 +1000
Subject: [Tutor] Implementing sets of user-defined objects
In-Reply-To: <2009502226-1279884215-cardhu_decombobulator_blackberry.rim.net-639053653-@bda188.bisx.produk.on.blackberry>
References: <2009502226-1279884215-cardhu_decombobulator_blackberry.rim.net-639053653-@bda188.bisx.produk.on.blackberry>
Message-ID: <201007232257.57223.steve@pearwood.info>

On Fri, 23 Jul 2010 09:22:55 pm mhw at doctors.net.uk wrote:
> Dear Tutors,
>
> I am tring to deal with some repeated data, and hence repeated
> objects (I construct objects from the data).
>
> I had hoped to use a set to uniquify the objects. However, I am
> having problems with defining uniqueness.

The objects need to define __eq__ and __hash__, and they must be 
immutable.

The easy way to do so is to inherit from something which is already 
immutable, say strings, ints, tuples or floats:

class MyObject(int):
    """Just like an int, but coloured purple."""
    def __init__(self, *args):
        self.colour = 'purple'


Otherwise, something like this recipe should do the job:

class MyObject(object):
    def __init__(self, a, b):
        self._value = (a, b)  # Private attribute, don't touch this.
    @property
    def value(self):
        return self._value
    def __eq__(self, other):
        if isinstance(other, MyObject): return self.value == other.value
        return NotImplemented  # Let the other object try.
    def __ne__(self, other):
        return not self == other
    def __hash__(self):
        return hash(self.value)
        

If x and y are instances of your class, and x equals y, then hash(x) 
*must* equal hash(y). (The opposite doesn't apply though... if x and y 
hash equal, they don't necessarily have to equal.)



-- 
Steven D'Aprano

From vineethrakesh at gmail.com  Fri Jul 23 15:22:54 2010
From: vineethrakesh at gmail.com (Vineeth Rakesh)
Date: Fri, 23 Jul 2010 09:22:54 -0400
Subject: [Tutor] position of an element in list:
Message-ID: <AANLkTinBt5VMu=M0FnJwu1G=CPU2eApmDEd55fm0oDF+@mail.gmail.com>

Hello all,

How to return the position of a character in a string. Say I have str1 =
"welcome to the world" if i want to return the position of the first
occurrence of "o" how to do it?

Thanks
Vin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100723/52aa9be1/attachment.html>

From rabidpoobear at gmail.com  Fri Jul 23 15:29:12 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 23 Jul 2010 08:29:12 -0500
Subject: [Tutor] position of an element in list:
In-Reply-To: <AANLkTinBt5VMu=M0FnJwu1G=CPU2eApmDEd55fm0oDF+@mail.gmail.com>
References: <AANLkTinBt5VMu=M0FnJwu1G=CPU2eApmDEd55fm0oDF+@mail.gmail.com>
Message-ID: <0608D619-3D23-4F35-80CA-61434B4A488B@gmail.com>

You can do it with any iterator.... Astr.index('o') I'm not sure what happens when there are multiple instances of 'o' though, check the docs on index.

Sent from my iPhone

On Jul 23, 2010, at 8:22 AM, Vineeth Rakesh <vineethrakesh at gmail.com> wrote:

> Hello all, 
> 
> How to return the position of a character in a string. Say I have str1 = "welcome to the world" if i want to return the position of the first occurrence of "o" how to do it?
> 
> Thanks
> Vin 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From steve at lonetwin.net  Fri Jul 23 15:13:43 2010
From: steve at lonetwin.net (steve)
Date: Fri, 23 Jul 2010 18:43:43 +0530
Subject: [Tutor] how i can change two lists into one directory
In-Reply-To: <AANLkTimeCKXEhGPivJDf329A7n3pN0XHKgHRsof1RdQR@mail.gmail.com>
References: <AANLkTin6KiA8cbvaFirpSFfRXE=MkVoUrexJUORmeh4+@mail.gmail.com>
	<AANLkTik7X2v8ajOoDB7lnz7rbrMT4bLDQic6zl9qVFZv@mail.gmail.com>
	<8F978CC0-7954-488D-8E32-8BDC7B5EB132@gmail.com>
	<AANLkTimeCKXEhGPivJDf329A7n3pN0XHKgHRsof1RdQR@mail.gmail.com>
Message-ID: <4C499587.2000605@lonetwin.net>

On 07/23/2010 08:01 AM, Robert wrote:
> looks like this guy figured out how to send email in a loop
>
User-Agent: Mutt/1.5.20 (2009-06-14)

Or just discovered Mutt but hasn't figured out the keybindings yet.


-- 
random spiel: http://lonetwin.net/
what i'm stumbling into: http://lonetwin.stumbleupon.com/

From cwitts at compuscan.co.za  Fri Jul 23 15:38:20 2010
From: cwitts at compuscan.co.za (Christian Witts)
Date: Fri, 23 Jul 2010 15:38:20 +0200
Subject: [Tutor] position of an element in list:
In-Reply-To: <AANLkTinBt5VMu=M0FnJwu1G=CPU2eApmDEd55fm0oDF+@mail.gmail.com>
References: <AANLkTinBt5VMu=M0FnJwu1G=CPU2eApmDEd55fm0oDF+@mail.gmail.com>
Message-ID: <4C499B4C.4070405@compuscan.co.za>

On 23/07/2010 15:22, Vineeth Rakesh wrote:
> Hello all,
>
> How to return the position of a character in a string. Say I have str1 
> = "welcome to the world" if i want to return the position of the first 
> occurrence of "o" how to do it?
>
> Thanks
> Vin
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>    

Strings have a function called index, which take a string argument which 
is what you're looking for.  So you can do str1.index('o') which would 
return 4.

-- 
Kind Regards,
Christian Witts


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100723/41c82346/attachment.html>

From steve at pearwood.info  Fri Jul 23 17:43:01 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 24 Jul 2010 01:43:01 +1000
Subject: [Tutor] position of an element in list:
In-Reply-To: <AANLkTinBt5VMu=M0FnJwu1G=CPU2eApmDEd55fm0oDF+@mail.gmail.com>
References: <AANLkTinBt5VMu=M0FnJwu1G=CPU2eApmDEd55fm0oDF+@mail.gmail.com>
Message-ID: <201007240143.01872.steve@pearwood.info>

On Fri, 23 Jul 2010 11:22:54 pm Vineeth Rakesh wrote:
> Hello all,
>
> How to return the position of a character in a string. Say I have
> str1 = "welcome to the world" if i want to return the position of the
> first occurrence of "o" how to do it?

str1.find("o") will return the index of the first "o", or -1 if not 
found.

str1.rfind("o") does the same, but searches from the right instead of 
the left.

str1.index("o") is like find, but it raises an exception instead of 
returning -1. Naturally there is a rindex as well.



-- 
Steven D'Aprano

From breamoreboy at yahoo.co.uk  Fri Jul 23 18:51:17 2010
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Fri, 23 Jul 2010 17:51:17 +0100
Subject: [Tutor] position of an element in list:
In-Reply-To: <201007240143.01872.steve@pearwood.info>
References: <AANLkTinBt5VMu=M0FnJwu1G=CPU2eApmDEd55fm0oDF+@mail.gmail.com>
	<201007240143.01872.steve@pearwood.info>
Message-ID: <i2chaf$bc6$1@dough.gmane.org>

On 23/07/2010 16:43, Steven D'Aprano wrote:
> On Fri, 23 Jul 2010 11:22:54 pm Vineeth Rakesh wrote:
>> Hello all,
>>
>> How to return the position of a character in a string. Say I have
>> str1 = "welcome to the world" if i want to return the position of the
>> first occurrence of "o" how to do it?
>
> str1.find("o") will return the index of the first "o", or -1 if not
> found.
>
> str1.rfind("o") does the same, but searches from the right instead of
> the left.
>
> str1.index("o") is like find, but it raises an exception instead of
> returning -1. Naturally there is a rindex as well.
>

For the OP and possibly others, all of these methods have optional start 
and end arguments.  Help for find shows:-

find(...)
     S.find(sub [,start [,end]]) -> int

     Return the lowest index in S where substring sub is found,
     such that sub is contained within s[start:end].  Optional
     arguments start and end are interpreted as in slice notation.

     Return -1 on failure.

Mark Lawrence



From alan.gauld at btinternet.com  Fri Jul 23 19:09:28 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 23 Jul 2010 18:09:28 +0100
Subject: [Tutor] position of an element in list:
References: <AANLkTinBt5VMu=M0FnJwu1G=CPU2eApmDEd55fm0oDF+@mail.gmail.com>
Message-ID: <i2cic8$f13$1@dough.gmane.org>


"Vineeth Rakesh" <vineethrakesh at gmail.com> wrote

> How to return the position of a character in a string. Say I have 
> str1 =
> "welcome to the world" if i want to return the position of the first
> occurrence of "o" how to do it?

Others have answered but don't forget Python's help() facility.

>>> help(str)

Would have probably got your answer a lot faster than posting a
question and waiting for replies.

We don't mind helping but for these kinds of question its usually
quicker to try a help(), dir() or even a Google search first. It saves
your time and ours.

HTH,

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



From amartin7211 at gmail.com  Fri Jul 23 19:48:49 2010
From: amartin7211 at gmail.com (Andrew Martin)
Date: Fri, 23 Jul 2010 13:48:49 -0400
Subject: [Tutor] Difficulty Understanding Example Code for Blender Script
In-Reply-To: <AANLkTikW3nD9CosnnLSKNhpskXRjKVNNFmWsGkSRURqB@mail.gmail.com>
References: <AANLkTinvCG_cafL0-95AIVyYjhDJxFgLsR1YIzPQ_E-Y@mail.gmail.com>
	<AANLkTikFMFwP8zWUc9z7c1d--wq_8P4ImWuzMOf6qRyE@mail.gmail.com>
	<AANLkTikW3nD9CosnnLSKNhpskXRjKVNNFmWsGkSRURqB@mail.gmail.com>
Message-ID: <AANLkTinkC4D5BMCAMngAW3aEYxd_TiZF70ni0sxcxJ+E@mail.gmail.com>

Oh ok. So orientation is an optional parameter. That makes sense. Alright
well thanks for the help

And yeah next time it would probably be better to try the blender forums.
thanks though

On Thu, Jul 22, 2010 at 3:06 AM, David Hutto <smokefloat at gmail.com> wrote:

> On Thu, Jul 22, 2010 at 2:47 AM, Marc Tompkins <marc.tompkins at gmail.com>
> wrote:
> > On Wed, Jul 21, 2010 at 9:48 PM, Andrew Martin <amartin7211 at gmail.com>
> > wrote:
> >>
> >> This code was part of a Blender script to build a 3d bar graph, so I
> don't
> >> know if understanding Blender is a prereq for understanding this code.
> The
> >> function is for the axis labels.
> >>
> >> def label(text,position,orientation='z'):
> >>     txt=Text3d.New('label')
> >>     txt.setText(text)
> >>     ob=Scene.GetCurrent().objects.new(txt)
> >>     ob.setLocation(*position)
> >>     if orientation=='x':
> >>         ob.setEuler(-pi/2.0,0,0)
> >>     elif orientation=='z':
> >>         ob.setEuler(0,0,pi/2.0)
> >>     print 'label %s at %s along %s' %(text,position,orientation)
> >>
> >>  I understand it for the most part except for the orientation part. I
> >> assume orientation is for the 3d text object, but how is it determined
> >> whether it is x or z?
> >
> > I don't use Blender myself, so this will be a more generic, high-level
> > answer...
> >>
> >> def label(text,position,orientation='z'):
> >
> > This definition specifies that label() takes two mandatory parameters -
> text
> > and position - and one optional parameter, orientation.  What makes
> > "orientation" optional is the fact that a default value is supplied:
> > "orientation='z'".  In other words, "orientation" is equal to "z" unless
> you
> > specify otherwise in your call to label().
>
> Seeing as how blender is 3d graphics, have you tried the 'newbie
> fidget with it', and typed in w(quaternion),x, or y to see what
> occurs. Also, have you looked into the hierarchy to see if z, which
> looks as though it's contained in a string, is an input variable
> declared elsewhere as an integer, or represents something else in it's
> usage. Z can mean global, or object orientation in blender from what I
> see.
>
> >
> > Take a look at this section of the Python docs:
> >
> http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions
> >
> > Hope that helps...
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100723/970b16c1/attachment.html>

From marris1031 at gmail.com  Fri Jul 23 20:23:41 2010
From: marris1031 at gmail.com (Mary Morris)
Date: Fri, 23 Jul 2010 12:23:41 -0600
Subject: [Tutor] decorators
Message-ID: <AANLkTimeoZ1_XQsw-5z_UZnejPQ_8qdAuiiKiVUYcofr@mail.gmail.com>

I'm trying to compile a list of decorators from the source code at my
office.
I did this by doing a

candidate_line.find("@")

because all of our decorators start with the @ symbol.  The problem I'm
having is that the email addresses that are included in the comments are
getting included in the list that is getting returned.
I was thinking I could do a candidate_line.find(".com") to set the email
addresses apart, but how do I tell the computer to not include the lines it
finds with ".com" in them in the list?

The part of my code that I'm hoping to include this in looks like this:



#parse out the names of the decorators from those lines
        return_decorators= []
        for ele in subset_lines:
                candidate_line, line_number = ele
                candidate_line = candidate_line.strip()
                i = candidate_line.find("(")
                j = candidate_line.find("#")
                #if () is in the last spot
                if i == -1:
                        #if () is in the last spot and the decorator is in a
comment
                        if j == 0:
                                #get rid of ( and #
                                candidate_line = candidate_line[2:i]
                        #if () is in the last spot and the decorator is not
in a comment
                        elif j != 0:
                                candidate_line = candidate_line[1:i]
                #if there are not ()'s in the last spot
                elif i != -1:
                        #if there are not ()'s, but the decorator is in a
comment
                        if j == 0:
                                candidate_line = candidate_line[2:]
                        #if there are not ()'s and the decorator isn't in a
comment
                        elif j != 0:
                                candidate_line = candidate_line[1:]
                elif candidate_line.find(".com"):
                        candidate_line != candidate_line

                return_decorators.append((line_number, candidate_line))


        return return_decorators
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100723/62540e87/attachment.html>

From shantanoo at gmail.com  Fri Jul 23 20:36:44 2010
From: shantanoo at gmail.com (=?UTF-8?B?4KS24KSC4KSk4KSo4KWC?=)
Date: Sat, 24 Jul 2010 00:06:44 +0530
Subject: [Tutor] decorators
In-Reply-To: <AANLkTimeoZ1_XQsw-5z_UZnejPQ_8qdAuiiKiVUYcofr@mail.gmail.com>
References: <AANLkTimeoZ1_XQsw-5z_UZnejPQ_8qdAuiiKiVUYcofr@mail.gmail.com>
Message-ID: <4C49E13C.8080204@gmail.com>

On Friday 23 July 2010 11:53 PM, Mary Morris wrote:
> I'm trying to compile a list of decorators from the source code at my 
> office.
> I did this by doing a
>
> candidate_line.find("@")

How about using something like

candidate_line.strip.startswith('@') and calculate_line.find('.') == -1

There are few more cases where above may fail. In that case you may want 
to use re module instead.
e.g.
@test_decorator # this is test comment.

>
> because all of our decorators start with the @ symbol.  The problem 
> I'm having is that the email addresses that are included in the 
> comments are getting included in the list that is getting returned.
> I was thinking I could do a candidate_line.find(".com") to set the 
> email addresses apart, but how do I tell the computer to not include 
> the lines it finds with ".com" in them in the list?
>
> The part of my code that I'm hoping to include this in looks like this:
>
>
>
> #parse out the names of the decorators from those lines
>         return_decorators= []
>         for ele in subset_lines:
>                 candidate_line, line_number = ele
>                 candidate_line = candidate_line.strip()
>                 i = candidate_line.find("(")
>                 j = candidate_line.find("#")
>                 #if () is in the last spot
>                 if i == -1:
>                         #if () is in the last spot and the decorator 
> is in a comment
>                         if j == 0:
>                                 #get rid of ( and #
>                                 candidate_line = candidate_line[2:i]
>                         #if () is in the last spot and the decorator 
> is not in a comment
>                         elif j != 0:
>                                 candidate_line = candidate_line[1:i]
>                 #if there are not ()'s in the last spot
>                 elif i != -1:
>                         #if there are not ()'s, but the decorator is 
> in a comment
>                         if j == 0:
>                                 candidate_line = candidate_line[2:]
>                         #if there are not ()'s and the decorator isn't 
> in a comment
>                         elif j != 0:
>                                 candidate_line = candidate_line[1:]
>  elif candidate_line.find(".com"):
>                         candidate_line != candidate_line
>                 return_decorators.append((line_number, candidate_line))
>         return return_decorators
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100724/a6a051a6/attachment-0001.html>

From steve at pearwood.info  Fri Jul 23 21:33:27 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 24 Jul 2010 05:33:27 +1000
Subject: [Tutor] decorators
In-Reply-To: <AANLkTimeoZ1_XQsw-5z_UZnejPQ_8qdAuiiKiVUYcofr@mail.gmail.com>
References: <AANLkTimeoZ1_XQsw-5z_UZnejPQ_8qdAuiiKiVUYcofr@mail.gmail.com>
Message-ID: <201007240533.28372.steve@pearwood.info>

On Sat, 24 Jul 2010 04:23:41 am Mary Morris wrote:
> I'm trying to compile a list of decorators from the source code at my
> office.
> I did this by doing a
>
> candidate_line.find("@")
>
> because all of our decorators start with the @ symbol.  The problem
> I'm having is that the email addresses that are included in the
> comments are getting included in the list that is getting returned.

First of all, to solve this problem *properly* you will need a proper 
parser to walk over the code and look for decorators, ignoring 
comments, skipping over strings, and similar. But that's hard, or at 
least I have no idea how to do it, so the alternative is a basic filter 
like you are doing.

If you're using Linux, Mac or some other Unix, the fastest solution 
would be to use grep. But ignoring that, think about what a decorator 
line is. You suggest above that a candidate line is a decorator if it 
has a @ sign in it. But that's incorrect. This is not a decorator:

    # send an email to steve at something.net or george at example.gov.au

But this might be:

    @decorator

So let's start with a simple little generator to return lines as a 
candidate decorator only if it *starts* with an ampersand:

def find_decorators(lines):
    """Return likely decorators from lines of text."""
    for line in lines:
        line = line.lstrip()  # ignore leading spaces
        if line.startswith('@'):
            yield line


That's still not fool-proof, only a proper Python parser will be 
fool-proof. This will be fooled by the *second* line in something like:

instructions = """If you have a problem with this, please call Fred
    @ accounts and tell him to reset the modem, then try again.
    If it still doesn't work blah blah blah """
   
So, not fool-proof, but it does the job.

You use find_decorators like this:

# Process them one at a time.
for decorator_line in find_decorators(open("source.py")):
    print decorator_line

To get them all at once, use:

list_of_decorators = list(find_decorators(open("source.py")))


How can we improve this? At the moment, find_decorators happily returns 
a line like this:

@decorator # This is a comment

but you probably don't care about the comment. So let's make a second 
filter to throw it away:

def remove_comments(lines):
    for line in lines:
        p = line.find('#')
        if p > -1:
            # Keep characters up to but not including p, 
            # ignoring trailing spaces
            yield line[:p].rstrip()
         else:
            yield line

And now apply this filter only to decorator lines:

f = open("source.py")
for decorator in remove_comments(find_decorators(f)):
    print decorator

To get them all at once:

f = open("source.py")
results = list(remove_comments(find_decorators(f)))


Again, this is not foolproof. If you have a decorator like this:

@decorator("this takes a string argument with a # inside it")

the filter will return:

@decorator("this takes a string argument with a

But, and I repeat myself like a broken record, if you want fool-proof, 
you need a proper parser, and that's hard.


-- 
Steven D'Aprano

From __peter__ at web.de  Fri Jul 23 23:19:00 2010
From: __peter__ at web.de (Peter Otten)
Date: Fri, 23 Jul 2010 23:19 +0200
Subject: [Tutor] decorators
References: <AANLkTimeoZ1_XQsw-5z_UZnejPQ_8qdAuiiKiVUYcofr@mail.gmail.com>
Message-ID: <i2d0va$1pi$1@dough.gmane.org>

Mary Morris wrote:

> I'm trying to compile a list of decorators from the source code at my
> office.
> I did this by doing a
> 
> candidate_line.find("@")
> 
> because all of our decorators start with the @ symbol.  The problem I'm
> having is that the email addresses that are included in the comments are
> getting included in the list that is getting returned.
> I was thinking I could do a candidate_line.find(".com") to set the email
> addresses apart, but how do I tell the computer to not include the lines
> it finds with ".com" in them in the list?

You can use the tokenize module to do the heavy lifting, see

http://docs.python.org/library/tokenize.html

Here's an example:

$ cat find_decos.py
import tokenize    
from collections import defaultdict

class Token:
    def __init__(self, token):
        self.string = token[1]
        self.lineno = token[2][0]

def find_decos(instream, filename, decos):
    tokens = (Token(token) for token in   
              tokenize.generate_tokens(instream.readline))
    for token in tokens:                                  
        if token.string == "@":                           
            lineno = token.lineno                         
            qname = [next(tokens).string]                 
            for token in tokens:                          
                if token.string == ".":                   
                    qname.append(next(tokens).string)     
                else:                                     
                    break                                 
            decos[".".join(qname)].append((lineno, filename))

def main():
    import sys
    files = sys.argv[1:]
    if not files:       
        # read filenames from stdin
        files = (line.strip() for line in sys.stdin)

    decorators = defaultdict(list)
    for filename in files:
        with open(filename) as instream:
            find_decos(instream, filename, decorators)
    for name in sorted(decorators):
        print name
        for location in decorators[name]:
            print "%8d %s" % location

if __name__ == "__main__":
    main()

if False:
    def f():
        """
        @not_a_decorator
        """
        return g
    # @not_a_decorator

    @alpha
    def first(x):
        return "user at example.com"

    @beta
    @gamma . one
    def second():
        pass

    @delta.two.three.four(*args)
    @epsilon(42)
    def third():
        pass

The if False:... suite is of course not a necessary part of the script, it's 
just a trick to cram in a few decorators for the script to find when you run 
it over itself:

$ python find_decos.py find_decos.py
alpha
      50 find_decos.py
beta
      54 find_decos.py
delta.two.three.four
      59 find_decos.py
epsilon
      60 find_decos.py
gamma.one
      55 find_decos.py

Alternatively you can feed filenames via stdin:

$ find /usr/lib/python2.6 -name \*.py | python find_decos.py | tail
     429 /usr/lib/python2.6/dist-
packages/usbcreator/frontends/kde/frontend.py
     434 /usr/lib/python2.6/dist-
packages/usbcreator/frontends/kde/frontend.py
     446 /usr/lib/python2.6/dist-
packages/usbcreator/frontends/kde/frontend.py
threaded
     166 /usr/lib/python2.6/dist-
packages/softwareproperties/kde/DialogMirror.py
withResolverLog
     572 /usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeCache.py
     858 /usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeCache.py
wraps
      81 /usr/lib/python2.6/contextlib.py
$

Peter


From coolankur2006 at gmail.com  Sat Jul 24 07:46:15 2010
From: coolankur2006 at gmail.com (ANKUR AGGARWAL)
Date: Sat, 24 Jul 2010 11:16:15 +0530
Subject: [Tutor] can i run the last saved input again
Message-ID: <AANLkTimp=cDuk2Ops4Tf3coEw6fqpU7tr5TSxoigvELW@mail.gmail.com>

hey this is a crazy question but i want to know it......
suppose i have this code

a=raw_input("enter the string :")
print a

then i type python prog.py

output:
enter the string:hello
hello


now i want to ask is there's any way that python remembers the input i gave
it to last time and it just give me the output when i again run python
prog.py?????? i mean i dont need to give input again. I just need to give
input only first time and when i run the prog again it will pick up the
previous one output
is it possible???
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100724/dda032b1/attachment.html>

From dextrous85 at gmail.com  Sat Jul 24 07:51:06 2010
From: dextrous85 at gmail.com (vishwajeet singh)
Date: Sat, 24 Jul 2010 11:21:06 +0530
Subject: [Tutor] can i run the last saved input again
In-Reply-To: <AANLkTimp=cDuk2Ops4Tf3coEw6fqpU7tr5TSxoigvELW@mail.gmail.com>
References: <AANLkTimp=cDuk2Ops4Tf3coEw6fqpU7tr5TSxoigvELW@mail.gmail.com>
Message-ID: <AANLkTi=1wsww0thFEFF4_avqWLXK=foY0n_7pzFreO0R@mail.gmail.com>

On Sat, Jul 24, 2010 at 11:16 AM, ANKUR AGGARWAL <coolankur2006 at gmail.com>wrote:

> hey this is a crazy question but i want to know it......
> suppose i have this code
>
> a=raw_input("enter the string :")
> print a
>
> then i type python prog.py
>
> output:
> enter the string:hello
> hello
>
>
> now i want to ask is there's any way that python remembers the input i gave
> it to last time and it just give me the output when i again run python
> prog.py?????? i mean i dont need to give input again. I just need to give
> input only first time and when i run the prog again it will pick up the
> previous one output
> is it possible???
>

 you need to serialize the input as everything goes out of memory once
program exits.



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


-- 
Vishwajeet Singh
+91-9657702154 | dextrous85 at gmail.com | http://bootstraptoday.com
Twitter: http://twitter.com/vishwajeets | LinkedIn:
http://www.linkedin.com/in/singhvishwajeet
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100724/5cef72df/attachment.html>

From steve at pearwood.info  Sat Jul 24 08:21:07 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 24 Jul 2010 16:21:07 +1000
Subject: [Tutor] can i run the last saved input again
In-Reply-To: <AANLkTimp=cDuk2Ops4Tf3coEw6fqpU7tr5TSxoigvELW@mail.gmail.com>
References: <AANLkTimp=cDuk2Ops4Tf3coEw6fqpU7tr5TSxoigvELW@mail.gmail.com>
Message-ID: <201007241621.07642.steve@pearwood.info>

On Sat, 24 Jul 2010 03:46:15 pm ANKUR AGGARWAL wrote:
[...]
> now i want to ask is there's any way that python remembers the input
> i gave it to last time and it just give me the output when i again
> run python prog.py?????? i mean i dont need to give input again. I
> just need to give input only first time and when i run the prog again
> it will pick up the previous one output
> is it possible???

Of course it is possible, many programs do it. You need to save the 
information you want to remember to a file, then later read it from 
disk.

Here's a skeleton of the idea:

look for the config file
if it exists:
    then read the answer from the file
if it doesn't exist, or you can't read from it:
    then ask the question
    try to save the answer in the config file
do whatever work you want with the answer

The ConfigParser module will be useful for writing the config file. 
Something like this should do the job:

import ConfigParser
ini = ConfigParser.ConfigParser()
if ini.read('mysettings.ini'):
    # File exists, so use it.
    answer = ini.get('main', 'answer')
else:
    # No config file. Get the answer from the user, and try to save it.
    answer = raw_input("Answer this question! ")
    answer = answer.strip()
    ini.add_section('main')
    ini.set('main', 'answer', answer)
    f = open('mysettings.ini', 'w')
    ini.write(f)
    f.close()

print "Your answer is", answer


although this needs better error checking, particularly where it tries 
to write the config file.


-- 
Steven D'Aprano

From anand.shashwat at gmail.com  Sat Jul 24 08:23:26 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Sat, 24 Jul 2010 11:53:26 +0530
Subject: [Tutor] can i run the last saved input again
In-Reply-To: <AANLkTimp=cDuk2Ops4Tf3coEw6fqpU7tr5TSxoigvELW@mail.gmail.com>
References: <AANLkTimp=cDuk2Ops4Tf3coEw6fqpU7tr5TSxoigvELW@mail.gmail.com>
Message-ID: <AANLkTimOZ_4=ttuM6zo5KKOmAh0Yks=e5eZ2p6A_v5F=@mail.gmail.com>

On Sat, Jul 24, 2010 at 11:16 AM, ANKUR AGGARWAL <coolankur2006 at gmail.com>wrote:

> hey this is a crazy question but i want to know it......
> suppose i have this code
>
> a=raw_input("enter the string :")
> print a
>
> then i type python prog.py
>
> output:
> enter the string:hello
> hello
>
>
> now i want to ask is there's any way that python remembers the input i gave
> it to last time and it just give me the output when i again run python
> prog.py?????? i mean i dont need to give input again. I just need to give
> input only first time and when i run the prog again it will pick up the
> previous one output
> is it possible???
>

Think about the consequences when python will start remembering the input.

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


-- 
~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100724/90e3ab8a/attachment.html>

From alan.gauld at btinternet.com  Sat Jul 24 10:00:21 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 24 Jul 2010 09:00:21 +0100
Subject: [Tutor] can i run the last saved input again
References: <AANLkTimp=cDuk2Ops4Tf3coEw6fqpU7tr5TSxoigvELW@mail.gmail.com>
Message-ID: <i2e6im$khr$1@dough.gmane.org>

"ANKUR AGGARWAL" <coolankur2006 at gmail.com> wrote

> hey this is a crazy question but i want to know it......
> suppose i have this code
>
> a=raw_input("enter the string :")
> print a
>
> now i want to ask is there's any way that python remembers the input 
> i gave
> it to last time and it just give me the output when i again run 
> python

No that is impossible, python is an interpreter and if it remembered
its input you would only ever be able to run one program. What you
want to do is get your program to remember its input, and that is
possible. It is very important you are clear in your mind what is 
python
and what is your code. You cannot change much in Python(*), you can
change anything in your code.

(*) Assuming we ignore hacking the Python source code of course!

All you need to do is save the input data to a file and when the 
program
starts, if the file exists read the input from that instead of stdin. 
You
may want to have a separate file for every user too...

You may want to add a flag to the program (-n say) that allows you to
specify that it should ignore the stored input should you wish to 
over-ride
that behaviour... You could also use a -f flag to force it to load a
particular input file...

Then the logic becomes:

if flag == 'f':
     datafilefile is command line arg
else datafile is userfile

if flag != 'n' and datafile exists:
    read input from datafile
else
   read input from user

HTH,

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



From steve at pearwood.info  Sat Jul 24 10:37:30 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 24 Jul 2010 18:37:30 +1000
Subject: [Tutor] can i run the last saved input again
In-Reply-To: <i2e6im$khr$1@dough.gmane.org>
References: <AANLkTimp=cDuk2Ops4Tf3coEw6fqpU7tr5TSxoigvELW@mail.gmail.com>
	<i2e6im$khr$1@dough.gmane.org>
Message-ID: <201007241837.31243.steve@pearwood.info>

On Sat, 24 Jul 2010 06:00:21 pm Alan Gauld wrote:
> "ANKUR AGGARWAL" <coolankur2006 at gmail.com> wrote
>
> > hey this is a crazy question but i want to know it......
> > suppose i have this code
> >
> > a=raw_input("enter the string :")
> > print a
> >
> > now i want to ask is there's any way that python remembers the
> > input i gave
> > it to last time and it just give me the output when i again run
> > python
>
> No that is impossible, python is an interpreter and if it remembered
> its input you would only ever be able to run one program. What you
> want to do is get your program to remember its input, and that is
> possible. It is very important you are clear in your mind what is
> python and what is your code.

You shouldn't have trimmed the rest of Ankur's post, because he clearly 
states he's talking about his program, not Python specifically:

"now i want to ask is there's any way that python remembers the input i 
gave it to last time and it just give me the output when i again run 
python prog.py?????? i mean i dont need to give input again. I just 
need to give input only first time and when i run the prog again it 
will pick up the previous one output is it possible???"

Well, for some definition of "clearly" :)


> You cannot change much in Python(*), you can 
> change anything in your code.

Actually, you can change a lot in Python, but often you shouldn't.

Any module you import, including builtins, can be monkey-patched 
(modified on the fly), although that's rightfully considered to be 
dangerous and best avoided except under very special circumstances.

You can't change syntax, or literals, or a handful of fixed objects like 
None, but otherwise most things in Python can be modified, if you know 
what you're doing and/or silly enough to modify them.

And of course when you start up Python, it reads a number of environment 
variables and config files, which give you an opportunity to have 
Python remember your input from last session. For example, I have a 
very minimal PYTHONSTARTUP file which automatically imports os and sys. 
I had also experimented with having it back-port functionality from 
versions 2.6 to 2.5. Some people use it to customize things like the 
prompt in the interactive interpreter, or install a tab-completion 
module, provide history which survives shutting down the interpreter 
(like most Linux shells already do), or otherwise provide added 
functionality such as that provided by (e.g.) IPython.

http://ipython.scipy.org/moin

So there are plenty of reasons to want Python to remember your input, 
and plenty of ways to do so.



-- 
Steven D'Aprano

From missive at hotmail.com  Sat Jul 24 17:34:20 2010
From: missive at hotmail.com (Lee Harr)
Date: Sat, 24 Jul 2010 20:04:20 +0430
Subject: [Tutor] can i run the last saved input again
Message-ID: <SNT106-W340A998432F42C027ADD77B1A40@phx.gbl>


> hey this is a crazy question but i want to know it......
> suppose i have this code
>
> a=raw_input("enter the string :")
> print a
>
> then i type python prog.py
>
> output:
> enter the string:hello
> hello
>
>
> now i want to ask is there's any way that python remembers the input i gave
> it to last time and it just give me the output when i again run python
> prog.py?


You've already received a number of different answers, so I will
tell you what I thought of when I read your (interesting, and not
really too crazy ;o) question:


Remember that input does not need to come from the keyboard.

I imagine that you are writing (and testing) a program, and you
are tired of always typing in the same input to test it.

One thing that you can do is put your input in to a separate file
and pipe that input in to your program to avoid all the typing...

My version of your program
$ cat echo.py 
a=raw_input("enter the string :")
print # Added a 2nd print, because ... well, you try it!
print a

Interactive ...
$ python echo.py 
enter the string :hello

hello

Make some test input ...
$ cat> test_input_1
hello!
$ cat> test_input_2
some different way of saying hello

(or use your text editor to create the input files)

Now use your test input files ...
$ python echo.py < test_input_1
enter the string :
hello!
$ python echo.py < test_input_2
enter the string :
some different way of saying hello


If you are clever, there is probably a way to "tee" your
input as you type it so that it goes both to your program
and in to a separate file to save it for later.

 		 	   		  
_________________________________________________________________
Hotmail: Trusted email with powerful SPAM protection.
https://signup.live.com/signup.aspx?id=60969

From alan.gauld at btinternet.com  Sat Jul 24 21:17:05 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 24 Jul 2010 20:17:05 +0100
Subject: [Tutor] can i run the last saved input again
References: <AANLkTimp=cDuk2Ops4Tf3coEw6fqpU7tr5TSxoigvELW@mail.gmail.com><i2e6im$khr$1@dough.gmane.org>
	<201007241837.31243.steve@pearwood.info>
Message-ID: <i2fe7j$3ht$1@dough.gmane.org>


"Steven D'Aprano" <steve at pearwood.info> wrote

> Actually, you can change a lot in Python, but often you shouldn't.

OK, I'll compromise and say you can change a bit.
But I define Python as the interpreter and standard library.

> Any module you import, including builtins, can be monkey-patched
> (modified on the fly), although that's rightfully considered to be
> dangerous and best avoided except under very special circumstances.

OK, But by definition you can only do that from your own code,
so I'd argue thats not Python changing. But I'd admit its a grey
area depending on how you define Python and Change...

> And of course when you start up Python, it reads a number of 
> environment
> variables and config files, which give you an opportunity to have
> Python remember your input from last session.

Actually thats true enough, and I hadn't thought about that.
You can create an arbitrary startup script that could potentially
even disable stdin or redirect it to an existing file such that it 
always
reads the same input. Probably a very bad idea, but you could do it...

> versions 2.6 to 2.5. Some people use it to customize things like the
> prompt in the interactive interpreter, or install a tab-completion
> module, provide history which survives shutting down the interpreter
> (like most Linux shells already do), or otherwise provide added
> functionality such as that provided by (e.g.) IPython.

Yes, and those are valid changes and the kinds of things I referred
to when I said you can''t change much. But those don't change how
Python runs a program.

My real concern was that it sounded like the OP was confused in
his mind about how much of the functionality was Python ( the
interpreter/language) and how much was his own code. Thats why
I made the distinction. It is important not to ascribe too much 
"magic"
to Python.

> So there are plenty of reasons to want Python to remember your 
> input,
> and plenty of ways to do so.

I had forgotten the startup options so with that in mind I'll admit 
that
yes, there are. Although for the specific example the OP gave they are
all either inappropriate or bad ideas.

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



From coolankur2006 at gmail.com  Sun Jul 25 00:57:32 2010
From: coolankur2006 at gmail.com (ANKUR AGGARWAL)
Date: Sun, 25 Jul 2010 04:27:32 +0530
Subject: [Tutor] hot to run python script at the startup
Message-ID: <AANLkTinpT4NS1xyr25yMkb0iViErvW1+FYwByMa5UtWJ@mail.gmail.com>

hey fellas i have a script abc.py with me....
i want to execute it as soon as i my linux gets start after entering
username and password thing (desktop thing)
how can i do that???
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100725/6cf423c4/attachment.html>

From alan.gauld at btinternet.com  Sun Jul 25 01:39:06 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 25 Jul 2010 00:39:06 +0100
Subject: [Tutor] hot to run python script at the startup
References: <AANLkTinpT4NS1xyr25yMkb0iViErvW1+FYwByMa5UtWJ@mail.gmail.com>
Message-ID: <i2ftir$bjq$1@dough.gmane.org>


"ANKUR AGGARWAL" <coolankur2006 at gmail.com> wrote

> hey fellas i have a script abc.py with me....
> i want to execute it as soon as i my linux gets start after entering
> username and password thing (desktop thing)
> how can i do that???

It depends on the shell that you use but if you use bash then you
can add a line to your .bash_profile or .bashrc file.

Which is best depends on whether you want it to run everytime
you login to your account (eg su from root) or only when you first
login etc. A full explanation can be found here:

http://www.linuxfromscratch.org/blfs/view/6.3/postlfs/profile.html

Different shells use different startup files.

This is more about Linux than Python.
To run the python script just add a line like:

python abc.py

in whichever file you decide is most appropriate.

HTH,

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



From delegbede at dudupay.com  Mon Jul 26 15:03:52 2010
From: delegbede at dudupay.com (Dipo Elegbede)
Date: Mon, 26 Jul 2010 14:03:52 +0100
Subject: [Tutor] django help....
Message-ID: <AANLkTik_T6WdiYvP7p8o66ymvAyzRUH26vkdQ9pwmj1c@mail.gmail.com>

hi,

I am doing reading on django....

what ook would you recommend for a beginner?

I have been trying to work with the documentations but get stock in between
and totally become lost.

this continous break is giving me too much headache to move on and i am
getting discouraged.

Please recommend a book for starters.

Thanks.

-- 
Elegbede Muhammed Oladipupo
OCA
+2348077682428
+2347042171716
www.dudupay.com
Mobile Banking Solutions | Transaction Processing | Enterprise Application
Development
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100726/b45b4760/attachment.html>

From huyslogic at gmail.com  Mon Jul 26 16:38:19 2010
From: huyslogic at gmail.com (Huy Ton That)
Date: Mon, 26 Jul 2010 10:38:19 -0400
Subject: [Tutor] django help....
In-Reply-To: <AANLkTik_T6WdiYvP7p8o66ymvAyzRUH26vkdQ9pwmj1c@mail.gmail.com>
References: <AANLkTik_T6WdiYvP7p8o66ymvAyzRUH26vkdQ9pwmj1c@mail.gmail.com>
Message-ID: <AANLkTik5gKLYw93s294aHN86Lph2br5twDNM_f9KmDoe@mail.gmail.com>

I highly recommend www.djangobook.com

The continuity is very good, and along the side of the book are comment
boxes with further insight from users.

After getting to about chapter 4, you should be able to toggle between
djangoproject.com's documentation and the rest of the djangobook for further
insight.

On Mon, Jul 26, 2010 at 9:03 AM, Dipo Elegbede <delegbede at dudupay.com>wrote:

> hi,
>
> I am doing reading on django....
>
> what ook would you recommend for a beginner?
>
> I have been trying to work with the documentations but get stock in between
> and totally become lost.
>
> this continous break is giving me too much headache to move on and i am
> getting discouraged.
>
> Please recommend a book for starters.
>
> Thanks.
>
> --
> Elegbede Muhammed Oladipupo
> OCA
> +2348077682428
> +2347042171716
> www.dudupay.com
> Mobile Banking Solutions | Transaction Processing | Enterprise Application
> Development
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100726/3a126406/attachment.html>

From fomcl at yahoo.com  Mon Jul 26 21:09:09 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Mon, 26 Jul 2010 12:09:09 -0700 (PDT)
Subject: [Tutor] xml question
Message-ID: <911929.88395.qm@web110705.mail.gq1.yahoo.com>

Hi,

I am making a data processing program that will use a configuration file. The file should contain information about: (1) source files used, (2) (intermediate) output files, (3) used parameters/estimation methods (4) manual data edits + datetime stamp + user name . I'd like to store this config file in xml. However, I've never created something like this before. Is this a suitable format, and, if so, what would the elementtree look like? Should I just use 'config'? or something similar as root, and the information elements 1 through 3 as child elements? And should the manual edits be stored as an element 'edit' with various attributes (the edit itself, the time stamp, etc.)?

Cheers!!

Albert-Jan



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100726/0a4b1970/attachment.html>

From joel.goldstick at gmail.com  Mon Jul 26 22:21:13 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 26 Jul 2010 16:21:13 -0400
Subject: [Tutor] xml question
In-Reply-To: <911929.88395.qm@web110705.mail.gq1.yahoo.com>
References: <911929.88395.qm@web110705.mail.gq1.yahoo.com>
Message-ID: <AANLkTikGo9GeQKb5pTVeAp1iuzs9_ZBUN+QXKDFMDSw0@mail.gmail.com>

On Mon, Jul 26, 2010 at 3:09 PM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:

> Hi,
>
> I am making a data processing program that will use a configuration file.
> The file should contain information about: (1) source files used, (2)
> (intermediate) output files, (3) used parameters/estimation methods (4)
> manual data edits + datetime stamp + user name . I'd like to store this
> config file in xml. However, I've never created something like this before.
> Is this a suitable format, and, if so, what would the elementtree look like?
> Should I just use 'config'  or something similar as root, and the
> information elements 1 through 3 as child elements? And should the manual
> edits be stored as an element 'edit' with various attributes (the edit
> itself, the time stamp, etc.)?
>
> Cheers!!
> Albert-Jan
>
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> All right, but apart from the sanitation, the medicine, education, wine,
> public order, irrigation, roads, a fresh water system, and public health,
> what have the Romans ever done for us?
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
I haven't used this, but I have heard others talk it up

http://docs.python.org/library/configparser.html
-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100726/7c4aae28/attachment.html>

From alan.gauld at btinternet.com  Tue Jul 27 01:32:55 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 27 Jul 2010 00:32:55 +0100
Subject: [Tutor] xml question
References: <911929.88395.qm@web110705.mail.gq1.yahoo.com>
	<AANLkTikGo9GeQKb5pTVeAp1iuzs9_ZBUN+QXKDFMDSw0@mail.gmail.com>
Message-ID: <i2l5v3$ou$1@dough.gmane.org>


"Joel Goldstick" <joel.goldstick at gmail.com> wrote

>> I am making a data processing program that will use a configuration 
>> file.
>> The file should contain information about: (1) source files used, 
>> (2)
>> (intermediate) output files, (3) used parameters/estimation methods 
>> (4)
>> manual data edits + datetime stamp + user name . I'd like to store 
>> this
>> config file in xml.

> I haven't used this, but I have heard others talk it up
>
> http://docs.python.org/library/configparser.html

Config parser is great for simple name/value pairs but for more 
complex
data XML is better. It sounds to me that this probably deserves an XML 
file...

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



From alan.gauld at btinternet.com  Tue Jul 27 01:38:11 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 27 Jul 2010 00:38:11 +0100
Subject: [Tutor] xml question
References: <911929.88395.qm@web110705.mail.gq1.yahoo.com>
Message-ID: <i2l68u$1i2$1@dough.gmane.org>


"Albert-Jan Roskam" <fomcl at yahoo.com> wrote

> The file should contain information about: ... (4) manual data edits 
> + datetime stamp + user name .
> I'd like to store this config file in xml.

Sounds sensible to me.

> ... what would the elementtree look like? Should I just use 'config' 
> or
> something similar as root, and the information elements 1 through 3 
> as
> child elements?

I'm no expert on XML but that sounds like a fair approach.

> And should the manual edits be stored as an element 'edit' with 
> various
> attributes (the edit itself, the time stamp, etc.)?

My limited experience says to avoid relying on attributes and stick to 
separate subnodes.
Attributes are OK for very simple values that are always specified but 
anything
at all complex or optional should have its own (possibly optional) 
node.

As always, design from the outside in - make the XML reflect the data
strucures you will be using in the code and the parsing will be easier
and the XML more intuitive.

YMMV...

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





From steve at pearwood.info  Tue Jul 27 02:29:53 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 27 Jul 2010 10:29:53 +1000
Subject: [Tutor] xml question
In-Reply-To: <911929.88395.qm@web110705.mail.gq1.yahoo.com>
References: <911929.88395.qm@web110705.mail.gq1.yahoo.com>
Message-ID: <201007271029.54243.steve@pearwood.info>

On Tue, 27 Jul 2010 05:09:09 am Albert-Jan Roskam wrote:
> Hi,
>
> I am making a data processing program that will use a configuration
> file. The file should contain information about: (1) source files
> used, (2) (intermediate) output files, (3) used parameters/estimation
> methods (4) manual data edits + datetime stamp + user name . I'd like
> to store this config file in xml.

Why XML?

Even though XML is plain text, it is *not* a human writable format, 
except perhaps for the simplest data. XML is one of those things which 
has become "the in-thing" and is used in all sorts of inappropriate 
places just because "everybody else uses XML". Even *supporters* of XML 
describe themselves as having "drunk the XML Kool-Aid". 

(For those who are unaware, "drinking the Kool-Aid" refers to the 
Reverend Jim Jones mass murder-suicide back in the 70s, when nearly a 
thousand cult members drank poison-laced Kool-Aid.)

XML is extremely verbose and inefficient. It has its uses, but the best 
advice I can give is, don't use XML unless you need to communicate with 
something that expects XML, or unless your data is so complex that you 
need XML.

Some alternatives:

If you're using Python 2.6 or better, you might consider the plistlib 
module for a thin wrapper around XML. 

JSON is often considered a more friendly format. Some people prefer YAML 
over JSON, although YAML isn't in the standard library.

If your data is in the form option:value, then ConfigParser 
(Windows-style ini files) may be all you need.

> However, I've never created
> something like this before. Is this a suitable format, and, if so,
> what would the elementtree look like? 

You tell us, it's your data :)


> Should I just use 'config'? or 
> something similar as root, and the information elements 1 through 3
> as child elements? And should the manual edits be stored as an
> element 'edit' with various attributes (the edit itself, the time
> stamp, etc.)?

How would you store the data in a Python class? Design your class first.



-- 
Steven D'Aprano

From davidheiserca at gmail.com  Tue Jul 27 03:14:44 2010
From: davidheiserca at gmail.com (davidheiserca at gmail.com)
Date: Mon, 26 Jul 2010 18:14:44 -0700
Subject: [Tutor] xml question
References: <911929.88395.qm@web110705.mail.gq1.yahoo.com>
	<201007271029.54243.steve@pearwood.info>
Message-ID: <F2A6D55651AD41349EFBB473A3D2C11A@dheiser>


I agree with Steven D'Aprano. Keep the code as simple as possible.

A simple text file with a variable/value pair on each line is very easy to 
parse and store in a Dictionary object. You can use any convenient 
delimiter; "=", ":", "$", ...

Nesting items under categories takes just a little more code logic, if you 
want to do that.

I have been doing this for many years. Simple is usually better.


----- Original Message ----- 
From: "Steven D'Aprano" <steve at pearwood.info>
>
> Why XML?
>
> Even though XML is plain text, it is *not* a human writable format,
> except perhaps for the simplest data. XML is one of those things which
> has become "the in-thing" and is used in all sorts of inappropriate
> places just because "everybody else uses XML". Even *supporters* of XML
> describe themselves as having "drunk the XML Kool-Aid".
>
> 


From quasipedia at gmail.com  Tue Jul 27 11:46:58 2010
From: quasipedia at gmail.com (Mac Ryan)
Date: Tue, 27 Jul 2010 11:46:58 +0200
Subject: [Tutor] xml question
In-Reply-To: <911929.88395.qm@web110705.mail.gq1.yahoo.com>
References: <911929.88395.qm@web110705.mail.gq1.yahoo.com>
Message-ID: <1280224018.7778.137.camel@jabbar>

On Mon, 2010-07-26 at 12:09 -0700, Albert-Jan Roskam wrote:
> I am making a data processing program that will use a configuration
> file. The file should contain information about: (1) source files
> used, (2) (intermediate) output files, (3) used parameters/estimation
> methods (4) manual data edits + datetime stamp + user name . I'd like
> to store this config file in xml. However, I've never created
> something like this before. Is this a suitable format, and, if so,
> what would the elementtree look like? Should I just use 'config'  or
> something similar as root, and the information elements 1 through 3 as
> child elements? And should the manual edits be stored as an element
> 'edit' with various attributes (the edit itself, the time stamp,
> etc.)?

I am with Steven on the fact that XML might not necessarily be the best
choice, unless you plan to use the configuration file with other
third-party programs, in which case the fact that XML has built-in
parsing libs for nearly all languages makes life of fellow developer
easier.

For the next project of mines, I am planning to use YAML (YAML Ain't a
Markup Language). I stumbled upon this format while toying around with
the google app engine, that uses it for storing your application
configuration data. IMO, YAML has the following prominent advantages:
   1) It is easy to read and edit by humans [think "markdown"]
   2) It has solid parsing libraries for Python
   3) It is far less verbose than XML
   4) It is consistent with Python "relevant whitespaces" [indentation
is used to define data structure hierarchy]

I have not yet got to the stage of writing code that use YAML (will take
two more weeks at best for me to get to that point), but should you go
down this road, I would love to hear back from you. [As I would love to
hear from anybody else who might have experience with YAML+Python]

Some links:
- http://en.wikipedia.org/wiki/YAML [good overview of the format]
- http://www.yaml.org/ [official site... when consistency with the
format makes a website hard to browse!]
- http://pyyaml.org/wiki/PyYAMLDocumentation [documentation of the
library for Python - pure Python code // can use a C library]

An example of YAML file to give you the taste of it:
> receipt:     Oz-Ware Purchase Invoice
> date:        2007-08-06
> 
> customer:
>     given:   Dorothy
>     family:  Gale
> 
> items:
>     - part_no:   A4786
>       descrip:   Water Bucket (Filled)
>       price:     1.47
>       quantity:  4
>     - part_no:   E1628
>       descrip:   High Heeled "Ruby" Slippers
>       price:     100.27
>       quantity:  1
> 
> bill-to:  &id001
>     street: |
>             123 Tornado Alley
>             Suite 16
>     city:   East Westville
>     state:  KS
> 
> ship-to:  *id001
> 
> specialDelivery:  >
>     Follow the Yellow Brick
>     Road to the Emerald City.
>     Pay no attention to the
>     man behind the curtain.

HTH,
Mac.



From quasipedia at gmail.com  Tue Jul 27 11:47:00 2010
From: quasipedia at gmail.com (Mac Ryan)
Date: Tue, 27 Jul 2010 11:47:00 +0200
Subject: [Tutor] django help....
In-Reply-To: <AANLkTik_T6WdiYvP7p8o66ymvAyzRUH26vkdQ9pwmj1c@mail.gmail.com>
References: <AANLkTik_T6WdiYvP7p8o66ymvAyzRUH26vkdQ9pwmj1c@mail.gmail.com>
Message-ID: <1280224020.7778.138.camel@jabbar>

On Mon, 2010-07-26 at 14:03 +0100, Dipo Elegbede wrote:
> what ook would you recommend for a beginner?

I am a django beginner myself. I did the tutorial first
(http://docs.djangoproject.com/en/dev/intro/tutorial01/) and now I am
very happy with "Practical Django Projects":
http://www.amazon.com/Practical-Django-Projects-Experts-Development/dp/1430219386

I assume that the fact I have a bit more than a year of "fooling around"
with Python (2.x series) makes this book easy to follow. If you
contrarily are not familiar with Python syntax then it might not be the
best choice.

As already mentioned by others, the Django book (http://djangobook.com)
is also a an excellent (and free!) alternative.

I've also begun to read "Pro Django" (http://prodjango.com/), which is
another excellent book, providing material to learn to leverage Python
itself better (beside Django). However - to put it as its author does -
"Pro Django isn?t for the faint of heart. It?s not for people who are
new to Django, and especially not those who are new to Python".

Best luck with your learning!
Mac.




From andreas.roehler at online.de  Tue Jul 27 15:12:31 2010
From: andreas.roehler at online.de (=?UTF-8?B?QW5kcmVhcyBSw7ZobGVy?=)
Date: Tue, 27 Jul 2010 15:12:31 +0200
Subject: [Tutor] xml question
In-Reply-To: <201007271029.54243.steve@pearwood.info>
References: <911929.88395.qm@web110705.mail.gq1.yahoo.com>
	<201007271029.54243.steve@pearwood.info>
Message-ID: <4C4EDB3F.10803@online.de>

Am 27.07.2010 02:29, schrieb Steven D'Aprano:
> On Tue, 27 Jul 2010 05:09:09 am Albert-Jan Roskam wrote:
>    
>> Hi,
>>
>> I am making a data processing program that will use a configuration
>> file. The file should contain information about: (1) source files
>> used, (2) (intermediate) output files, (3) used parameters/estimation
>> methods (4) manual data edits + datetime stamp + user name . I'd like
>> to store this config file in xml.
>>      
> Why XML?
>
> Even though XML is plain text, it is *not* a human writable format,
> except perhaps for the simplest data. XML is one of those things which
> has become "the in-thing" and is used in all sorts of inappropriate
> places just because "everybody else uses XML". Even *supporters* of XML
> describe themselves as having "drunk the XML Kool-Aid".
>
> (For those who are unaware, "drinking the Kool-Aid" refers to the
> Reverend Jim Jones mass murder-suicide back in the 70s, when nearly a
> thousand cult members drank poison-laced Kool-Aid.)
>    

Be careful spreading information you didn't research thoroughly yourself.
This world is upside-down.

Andreas

--
https://code.launchpad.net/~a-roehler/python-mode
https://code.launchpad.net/s-x-emacs-werkstatt/


> XML is extremely verbose and inefficient. It has its uses, but the best
> advice I can give is, don't use XML unless you need to communicate with
> something that expects XML, or unless your data is so complex that you
> need XML.
>
> Some alternatives:
>
> If you're using Python 2.6 or better, you might consider the plistlib
> module for a thin wrapper around XML.
>
> JSON is often considered a more friendly format. Some people prefer YAML
> over JSON, although YAML isn't in the standard library.
>
> If your data is in the form option:value, then ConfigParser
> (Windows-style ini files) may be all you need.
>
>    
>> However, I've never created
>> something like this before. Is this a suitable format, and, if so,
>> what would the elementtree look like?
>>      
> You tell us, it's your data :)
>
>
>    
>> Should I just use 'config'  or
>> something similar as root, and the information elements 1 through 3
>> as child elements? And should the manual edits be stored as an
>> element 'edit' with various attributes (the edit itself, the time
>> stamp, etc.)?
>>      
> How would you store the data in a Python class? Design your class first.
>
>
>
>    


From kpguy1975 at gmail.com  Tue Jul 27 15:31:35 2010
From: kpguy1975 at gmail.com (Vikram K)
Date: Tue, 27 Jul 2010 19:01:35 +0530
Subject: [Tutor] nested list help
Message-ID: <AANLkTi=uYt+kFC=552NLED_yyL6RAUE2B8VMf+F5r_pP@mail.gmail.com>

Suppose i have this nested list:

>>> x
[['NM100', 3, 4, 5, 6, 7], ['NM100', 10, 11, 12, 13], ['NM200', 15, 16, 17]]
>>> for i in x:
...   print i
...
['NM100', 3, 4, 5, 6, 7]
['NM100', 10, 11, 12, 13]
['NM200', 15, 16, 17]
>>>

how do i obtain from the above the following nested list:

>>> z
[['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13], ['NM200', 15, 16, 17]]
>>> for i in z:
...   print i
...
['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13]
['NM200', 15, 16, 17]
>>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100727/8685b6df/attachment.html>

From evert.rol at gmail.com  Tue Jul 27 15:48:38 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Tue, 27 Jul 2010 15:48:38 +0200
Subject: [Tutor] nested list help
In-Reply-To: <AANLkTi=uYt+kFC=552NLED_yyL6RAUE2B8VMf+F5r_pP@mail.gmail.com>
References: <AANLkTi=uYt+kFC=552NLED_yyL6RAUE2B8VMf+F5r_pP@mail.gmail.com>
Message-ID: <3B4BFE79-CD1C-43FB-986A-5772D045403D@gmail.com>

> Suppose i have this nested list:
> 
> >>> x
> [['NM100', 3, 4, 5, 6, 7], ['NM100', 10, 11, 12, 13], ['NM200', 15, 16, 17]]
> >>> for i in x:
> ...   print i
> ... 
> ['NM100', 3, 4, 5, 6, 7]
> ['NM100', 10, 11, 12, 13]
> ['NM200', 15, 16, 17]
> >>> 
> 
> how do i obtain from the above the following nested list:
> 
> >>> z
> [['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13], ['NM200', 15, 16, 17]]

You're not saying exactly how you go from one list to the other (ie, what criterion you use to combine the inner lists).
You could remove combine the first two lists using extend(), whereby you pass all but the first element of the second inner list to extend(): list1.extend(list2[1:]). Or simply list1+list2[1:].
If you're not concerned about the order of the elements (though I guess you are), you could do things like list(set(list1+list2)).
On the other hand, if you want to combine lists based on their first element, consider using dictionaries and extend lists which have the same key. Depending on how you create the lists (eg, when reading columns from a file), you can actually do this during creationi.
Otherwise, a (double) for-loop and an if-statement would probably work and be relatively straightforward, but I guess that would be rather un-Pythonesque.


> >>> for i in z:
> ...   print i
> ... 
> ['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13]
> ['NM200', 15, 16, 17]
> >>> 



From rdmoores at gmail.com  Tue Jul 27 16:22:38 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Tue, 27 Jul 2010 07:22:38 -0700
Subject: [Tutor] need help with msvcrt.getch()
Message-ID: <AANLkTikfEWYTzmKOd1ibTe_WVca=TGzsrJgbvAv6ce8r@mail.gmail.com>

Python 3.1 on Vista.

Please see <http://tutoree7.pastebin.com/f3TaxDBc>.

I'm trying to recall what I used to know, thus this simple script. But 'y'
or 'q' do nothing. What's wrong?

Thanks,

Dick Moores
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100727/3944f137/attachment.html>

From mail at timgolden.me.uk  Tue Jul 27 16:36:31 2010
From: mail at timgolden.me.uk (Tim Golden)
Date: Tue, 27 Jul 2010 15:36:31 +0100
Subject: [Tutor] need help with msvcrt.getch()
In-Reply-To: <AANLkTikfEWYTzmKOd1ibTe_WVca=TGzsrJgbvAv6ce8r@mail.gmail.com>
References: <AANLkTikfEWYTzmKOd1ibTe_WVca=TGzsrJgbvAv6ce8r@mail.gmail.com>
Message-ID: <4C4EEEEF.5070401@timgolden.me.uk>

On 27/07/2010 15:22, Richard D. Moores wrote:
> Python 3.1 on Vista.
>
> Please see<http://tutoree7.pastebin.com/f3TaxDBc>.
>
> I'm trying to recall what I used to know, thus this simple script. But 'y'
> or 'q' do nothing. What's wrong?

msvcrt.getch returns bytes on Python 3.1; you're comparing against
string. Try

if key == b'y':
   ... etc.

TJG

From airscorp at otenet.gr  Tue Jul 27 16:41:52 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Tue, 27 Jul 2010 17:41:52 +0300
Subject: [Tutor] nested list help
In-Reply-To: <3B4BFE79-CD1C-43FB-986A-5772D045403D@gmail.com>
References: <AANLkTi=uYt+kFC=552NLED_yyL6RAUE2B8VMf+F5r_pP@mail.gmail.com>
	<3B4BFE79-CD1C-43FB-986A-5772D045403D@gmail.com>
Message-ID: <4C4EF030.1010000@otenet.gr>

On 07/27/2010 04:48 PM, Evert Rol wrote:
>
> On the other hand, if you want to combine lists based on their first element, consider using dictionaries and extend lists which have the same key. Depending on how you create the lists (eg, when reading columns from a file), you can actually do this during creationi.
>

I'm very much with Everet on this one. Your data would be better 
contained in a dictionary as such:
x = {'NM100': [3, 4, 5, 6, 7, 10, 11, 12, 13],
      'NM200': [15, 16, 17]}

Choosing your data structure is, most of the time, as important as the 
rest of your code.

The rest of the time, the format of your input is not something you can 
control so:
If your data is already on a nested list, as it's on your example, you 
can convert them quite easily to a dictionary.
You then can manipulate them with ease, and if you do want them back on 
nested list format, convert them back.

Here's a very quick script I wrote on how to do it.
Please read it through and hit me with questions on what you don't 
understand.

-------------------------------------------------------------
input = [['NM100', 3, 4, 5, 6, 7],
          ['NM100', 10, 11, 12, 13],
          ['NM200', 15, 16, 17]]

# Convert and combine the input into a dictionary
output_dict = {}
for entry in input:
     key = entry[0]
     values = entry[1:]
     if key in output_dict:
         output_dict[key].extend(values)
     else:
         output_dict[key] = values
print output_dict

# Convert the dictionary back into a nested list
output = []
for key in output_dict:
     entry = output_dict[key]
     entry.insert(0, key)
     output.append(entry)

print output
----------------------------------------------------------------

Of course, my script is very basic and it doesn't tend to a lot of 
things you'd might want, like eliminating double values or sorting, but 
it should start you on your path.

Nick


From airscorp at otenet.gr  Tue Jul 27 16:51:47 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Tue, 27 Jul 2010 17:51:47 +0300
Subject: [Tutor] need help with msvcrt.getch()
In-Reply-To: <AANLkTikfEWYTzmKOd1ibTe_WVca=TGzsrJgbvAv6ce8r@mail.gmail.com>
References: <AANLkTikfEWYTzmKOd1ibTe_WVca=TGzsrJgbvAv6ce8r@mail.gmail.com>
Message-ID: <4C4EF283.3040306@otenet.gr>

On 07/27/2010 05:22 PM, Richard D. Moores wrote:
> Python 3.1 on Vista.
>
> Please see <http://tutoree7.pastebin.com/f3TaxDBc>.
>
> I'm trying to recall what I used to know, thus this simple script. But 
> 'y' or 'q' do nothing. What's wrong?
>
> Thanks,
>
> Dick Moores
>    
Hi Dick!
I'm not on Windows here so this might be a wild guess.

 From the documentation I gather that msvcrt can work either on binary 
or text mode.
Perhaps you operate in the wrong one and need to switch with 
msvcrt.setmode(/)

Anyway, insert some print lines to see what exactly is it that /getch() 
gets and debug from there

Nick

From rdmoores at gmail.com  Tue Jul 27 17:12:42 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Tue, 27 Jul 2010 08:12:42 -0700
Subject: [Tutor] need help with msvcrt.getch()
In-Reply-To: <4C4EEEEF.5070401@timgolden.me.uk>
References: <AANLkTikfEWYTzmKOd1ibTe_WVca=TGzsrJgbvAv6ce8r@mail.gmail.com> 
	<4C4EEEEF.5070401@timgolden.me.uk>
Message-ID: <AANLkTinqxyJvTaMhLwqb8T=T-6Ld9idRVbcRvz37pPj9@mail.gmail.com>

On Tue, Jul 27, 2010 at 07:36, Tim Golden <mail at timgolden.me.uk> wrote:

> On 27/07/2010 15:22, Richard D. Moores wrote:
>
>> Python 3.1 on Vista.
>>
>> Please see<http://tutoree7.pastebin.com/f3TaxDBc>.
>>
>> I'm trying to recall what I used to know, thus this simple script. But 'y'
>> or 'q' do nothing. What's wrong?
>>
>
> msvcrt.getch returns bytes on Python 3.1; you're comparing against
> string. Try
>
> if key == b'y':
>  ... etc.
>

Yes! That did it.

Thank you.

Dick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100727/587ff28c/attachment.html>

From rdmoores at gmail.com  Tue Jul 27 17:57:12 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Tue, 27 Jul 2010 08:57:12 -0700
Subject: [Tutor] need help with msvcrt.getch()
In-Reply-To: <4C4EF283.3040306@otenet.gr>
References: <AANLkTikfEWYTzmKOd1ibTe_WVca=TGzsrJgbvAv6ce8r@mail.gmail.com> 
	<4C4EF283.3040306@otenet.gr>
Message-ID: <AANLkTi=g7n0U0MyEyN+bnvcos8zCXJp8ZVKRQYaDWnE=@mail.gmail.com>

On Tue, Jul 27, 2010 at 07:51, Nick Raptis <airscorp at otenet.gr> wrote:

> On 07/27/2010 05:22 PM, Richard D. Moores wrote:
>
>> Python 3.1 on Vista.
>>
>> Please see <http://tutoree7.pastebin.com/f3TaxDBc>.
>>
>> I'm trying to recall what I used to know, thus this simple script. But 'y'
>> or 'q' do nothing. What's wrong?
>>
>> Thanks,
>>
>> Dick Moores
>>
>>
> Hi Dick!
> I'm not on Windows here so this might be a wild guess.
>
> From the documentation I gather that msvcrt can work either on binary or
> text mode.
> Perhaps you operate in the wrong one and need to switch with
> msvcrt.setmode(/)
>
> Anyway, insert some print lines to see what exactly is it that /getch()
> gets and debug from there
>

On <http://docs.python.org/py3k/library/msvcrt.html#module-msvcrt> I find
 msvcrt.setmode(*fd*,
*flags*)?<http://docs.python.org/py3k/library/msvcrt.html#msvcrt.setmode>
Set
the line-end translation mode for the file descriptor *fd*. To set it to
text mode, *flags* should be
os.O_TEXT<http://docs.python.org/py3k/library/os.html#os.O_TEXT>;
for binary, it should be
os.O_BINARY<http://docs.python.org/py3k/library/os.html#os.O_BINARY>
.But I don't understand how to implement this. I've tried <
http://tutoree7.pastebin.com/gYbq67Ja>, but get

C:\P31Working>test_getch1b.py
Traceback (most recent call last):
  File "C:\P31Working\test_getch1b.py", line 7, in <module>
    msvcrt.setmode(1,os._TEXT)
AttributeError: 'module' object has no attribute '_TEXT'

Nick, could you spell out for me what you are suggesting? I like the
possibility of not having to use b'y' instead of 'y'.

Dick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100727/2639d1e3/attachment.html>

From ahmedn82 at hotmail.com  Tue Jul 27 18:04:21 2010
From: ahmedn82 at hotmail.com (Ahmed AL-Masri)
Date: Wed, 28 Jul 2010 00:04:21 +0800
Subject: [Tutor] append in new file??
Message-ID: <BAY127-DS13299BD0818A87919D347FCEA70@phx.gbl>

hello;

I need help in append a data in new file. the problem is the new data are generated in every run.
so at the end I should get all the changes in one file (means for all running) if I run 2 times so should get couple of data set.
note all outputs in txt file.
ex:
this is the first run data 
1.0362 1.015 1.011 0.9948 1.0024 0.9936
0.9129 0.9184 0.9868 0.9682 0.975 0.8953
1.0627 1.0517 1.0306 1.0387 1.0501 1.0485
1.0467 1.0342 1.0389 1.0109 1.0107 1.0066

next run the data changes in the same output file 
1.020 1.043 1.111 0.343 1.454 1.999
0.9129 0.9184 0.9868 0.9682 0.975 0.8953
1.0555 1.2222 1.333 1.4444 1.2222 1.2222
1.1111 1.1111 1.1111 1.1111 1.1111 1.1111

the appended file should be 
1.0362 1.015 1.011 0.9948 1.0024 0.9936
0.9129 0.9184 0.9868 0.9682 0.975 0.8953
1.0627 1.0517 1.0306 1.0387 1.0501 1.0485
1.0467 1.0342 1.0389 1.0109 1.0107 1.0066
1.020 1.043 1.111 0.343 1.454 1.999
0.9129 0.9184 0.9868 0.9682 0.975 0.8953
1.0555 1.2222 1.333 1.4444 1.2222 1.2222
1.1111 1.1111 1.1111 1.1111 1.1111 1.1111

more run more data will generate.

I tried so many times without any result.
t=open('old data'.txt')
d=open('new data.txt','w')

while True:
    line=t.readline()
    if len(line) ==0:
  break
    volt=line.split()
    volt=map(float, volt)
    for i in range (len(line.split())):
        d.write(str(volt[i])+' ')
    d.write('\n')
d.close

but this only bring as same as the old file.

also I found some codes from the committee and tried but still not working.
import sys

def check_dup(fd1):
    print fd1
    fd1.seek(0,0)
    list1=[]
    while not done:
        x = fd1.readline()
        if x == "":
            break
        else:
            list1.append(x)
    return list1


fname = 'new data.txt'

fd = open(fname,'a+')
print fd

t=open('old data'.txt'
while not done:
    while True:
        line=t.readline()
        if len(line) ==0:
            break
        volt=line.split()
        volt=map(float, volt)
        for i in range (len(line.split())):
            print str
            flag = check_dup(fd)
            print flag
            fd.seek(0,2)
            fd.write(str(volt[i]) + ' ')
        fd.write('\n')
    break

looking forward for prompt response,
best regards,

Ahmed Naufal  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/d7924a73/attachment.html>

From alan.gauld at btinternet.com  Tue Jul 27 18:09:32 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 27 Jul 2010 17:09:32 +0100
Subject: [Tutor] need help with msvcrt.getch()
References: <AANLkTikfEWYTzmKOd1ibTe_WVca=TGzsrJgbvAv6ce8r@mail.gmail.com>
Message-ID: <i2n0bo$eql$1@dough.gmane.org>


"Richard D. Moores" <rdmoores at gmail.com> wrote

> Please see <http://tutoree7.pastebin.com/f3TaxDBc>.
>
> I'm trying to recall what I used to know, thus this simple script. 
> But 'y'
> or 'q' do nothing. What's wrong?

I don't think you need kbhit() or the sleep(.1)
The if kbhit test will only pass if the key is actually hit at that 
time.
Often it won't be so you will miss it.

I think getch() will wait for a key to be hit.

But thats from memory and I'm too busy to try it out right now.

Alan G. 



From jjcrump at uw.edu  Tue Jul 27 18:44:02 2010
From: jjcrump at uw.edu (Jon Crump)
Date: Tue, 27 Jul 2010 09:44:02 -0700
Subject: [Tutor] lambda vs list comp
Message-ID: <AANLkTiniGBidmezwO4rSwy0=mttU5hBF9DRQVhtp9dLO@mail.gmail.com>

Just as a matter of curiosity piqued by having to understand someone
else's code. Is the difference here just a matter of style, or is one
better somehow than the other?

>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> ','.join([str(x) for x in l])
'0,1,2,3,4,5,6,7,8,9,10'

>>> ','.join(map(lambda x:str(x), l))
'0,1,2,3,4,5,6,7,8,9,10'

From joel.goldstick at gmail.com  Tue Jul 27 18:47:12 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 27 Jul 2010 12:47:12 -0400
Subject: [Tutor] append in new file??
In-Reply-To: <BAY127-DS13299BD0818A87919D347FCEA70@phx.gbl>
References: <BAY127-DS13299BD0818A87919D347FCEA70@phx.gbl>
Message-ID: <AANLkTik1Z-GjWiNYes=pLkK6RKiuhpyqinFSj8exuKJp@mail.gmail.com>

2010/7/27 Ahmed AL-Masri <ahmedn82 at hotmail.com>

>  hello;
>
> I need help in append a data in new file. the problem is the new data are
> generated in every run.
> so at the end I should get all the changes in one file (means for all
> running) if I run 2 times so should get couple of data set.
> note all outputs in txt file.
>

You need to use append mode when you open the file

http://docs.python.org/library/functions.html?highlight=open#open



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100727/c7fb8fc0/attachment.html>

From quasipedia at gmail.com  Tue Jul 27 18:53:45 2010
From: quasipedia at gmail.com (Mac Ryan)
Date: Tue, 27 Jul 2010 18:53:45 +0200
Subject: [Tutor] lambda vs list comp
In-Reply-To: <AANLkTiniGBidmezwO4rSwy0=mttU5hBF9DRQVhtp9dLO@mail.gmail.com>
References: <AANLkTiniGBidmezwO4rSwy0=mttU5hBF9DRQVhtp9dLO@mail.gmail.com>
Message-ID: <1280249625.12064.22.camel@jabbar>

On Tue, 2010-07-27 at 09:44 -0700, Jon Crump wrote:
> Just as a matter of curiosity piqued by having to understand someone
> else's code. Is the difference here just a matter of style, or is one
> better somehow than the other?
> 
> >>> l
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> 
> >>> ','.join([str(x) for x in l])
> '0,1,2,3,4,5,6,7,8,9,10'
> 
> >>> ','.join(map(lambda x:str(x), l))
> '0,1,2,3,4,5,6,7,8,9,10'

Considering that "readability metters" I would go for none of the two,
but for:

','.join(map(str, l))

(Indeed defining a lambda function that simply uses "str" is redundant)

Just my personal take on this, though!
Mac.


From roadierich at googlemail.com  Tue Jul 27 19:31:12 2010
From: roadierich at googlemail.com (Rich Lovely)
Date: Tue, 27 Jul 2010 18:31:12 +0100
Subject: [Tutor] lambda vs list comp
In-Reply-To: <1280249625.12064.22.camel@jabbar>
References: <AANLkTiniGBidmezwO4rSwy0=mttU5hBF9DRQVhtp9dLO@mail.gmail.com> 
	<1280249625.12064.22.camel@jabbar>
Message-ID: <AANLkTinWLdUPsM9Q0o1a5spTr4+3MRZhPEp2ELO3qFs_@mail.gmail.com>

On 27 July 2010 17:53, Mac Ryan <quasipedia at gmail.com> wrote:
> On Tue, 2010-07-27 at 09:44 -0700, Jon Crump wrote:
>> Just as a matter of curiosity piqued by having to understand someone
>> else's code. Is the difference here just a matter of style, or is one
>> better somehow than the other?
>>
>> >>> l
>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>
>> >>> ','.join([str(x) for x in l])
>> '0,1,2,3,4,5,6,7,8,9,10'
>>
>> >>> ','.join(map(lambda x:str(x), l))
>> '0,1,2,3,4,5,6,7,8,9,10'
>
> Considering that "readability metters" I would go for none of the two,
> but for:
>
> ','.join(map(str, l))
>
> (Indeed defining a lambda function that simply uses "str" is redundant)
>
> Just my personal take on this, though!
> Mac.
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

There's very little difference between the two in the example you're
using, in python 2.x.  It's a different matter if you want to do
something slightly more complex, or of you're using Python 3.

The benefit of list comprehensions is that they can take a number of
iterables and filter clauses:

>>> [x+y for x in range(3) for y in range(3) if x!=y]
[1, 2, 1, 3, 2, 3]

I can't see any easy way of doing something like that using just map,
fliter and so on.

In python 3, map is a different sort of beast.  Instead of returning a
list, it returns an iterable called a "mapping".  It stores the
original list and the function, and only calls the function when you
ask it for the next value.  You can get similar behaviour in python2
using the imap function in the itertools module.  It's extremely
useful if you need to deal with massive lists of millions of elements
- where making the list every time would take too long.

-- 
Rich "Roadie Rich" Lovely

Just because you CAN do something, doesn't necessarily mean you SHOULD.
In fact, more often than not, you probably SHOULDN'T.? Especially if I
suggested it.

10 re-discover BASIC
20 ???
30 PRINT "Profit"
40 GOTO 10

From rdmoores at gmail.com  Tue Jul 27 19:47:12 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Tue, 27 Jul 2010 10:47:12 -0700
Subject: [Tutor] need help with msvcrt.getch()
In-Reply-To: <i2n0bo$eql$1@dough.gmane.org>
References: <AANLkTikfEWYTzmKOd1ibTe_WVca=TGzsrJgbvAv6ce8r@mail.gmail.com> 
	<i2n0bo$eql$1@dough.gmane.org>
Message-ID: <AANLkTi=yZ+NHB-22kaGU+N3TN9eKuPS_x6f6x-u79Lzf@mail.gmail.com>

On Tue, Jul 27, 2010 at 09:09, Alan Gauld <alan.gauld at btinternet.com> wrote:

>
> "Richard D. Moores" <rdmoores at gmail.com> wrote
>
>
>  Please see <http://tutoree7.pastebin.com/f3TaxDBc>.
>>
>> I'm trying to recall what I used to know, thus this simple script. But 'y'
>> or 'q' do nothing. What's wrong?
>>
>
> I don't think you need kbhit()


I tried taking it out. You're right, Alan, I don't need it. See <
http://tutoree7.pastebin.com/N8hdyqLZ>


> or the sleep(.1)
>

Testing with and without sleep(.001) shows that sleep(.001) cuts the CPU
usage dramatically, from ~50% to ~5%!

The if kbhit test will only pass if the key is actually hit at that time.
> Often it won't be so you will miss it.
>

I didn't see that, but with a bigger loop I may, I suppose.


> I think getch() will wait for a key to be hit.
>
> But thats from memory and I'm too busy to try it out right now.
>

So I tried putting a counter, c, in the loop. See <
http://tutoree7.pastebin.com/9Q8u3wLw>.

It seems you're correct, in that if I hit 'y' 10 times and then 'q' to
close, I'll get "c = 11". 5 'x's and 5 'y's and a 'q' also gets "c = 11", of
course. Out of curiosity, I tried holding down 'z' (i.e., neither 'y' nor
'q' for exactly 10 seconds, and then hit 'q'. Got "c = 267".

Thanks, Alan.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100727/2f171bb7/attachment.html>

From fomcl at yahoo.com  Tue Jul 27 20:25:49 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Tue, 27 Jul 2010 11:25:49 -0700 (PDT)
Subject: [Tutor] xml question
In-Reply-To: <1280224018.7778.137.camel@jabbar>
Message-ID: <309838.69935.qm@web110704.mail.gq1.yahoo.com>

Thank you all for your replies; they were most useful! I've never made a connection between xml and mass-suicide? ---interesting. ;-) Yaml seems a good choice (I didn't llook at config parser yet). In my office, we use Python and R (among other tools) and therfore it seems best not to use some pure python config file format. I agree that the readability/editability (by humans) of a yaml file is a huge advantage. Today I experimented with the yaml library of R and it felt very intuitive. I expect this will be the same for Python (not in the last place because Python is such a *beautiful*, clear language ;-)

Cheers!!

Albert-Jan



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

--- On Tue, 7/27/10, Mac Ryan <quasipedia at gmail.com> wrote:

From: Mac Ryan <quasipedia at gmail.com>
Subject: Re: [Tutor] xml question
To: tutor at python.org
Date: Tuesday, July 27, 2010, 11:46 AM

On Mon, 2010-07-26 at 12:09 -0700, Albert-Jan Roskam wrote:
> I am making a data processing program that will use a configuration
> file. The file should contain information about: (1) source files
> used, (2) (intermediate) output files, (3) used parameters/estimation
> methods (4) manual data edits + datetime stamp + user name . I'd like
> to store this config file in xml. However, I've never created
> something like this before. Is this a suitable format, and, if so,
> what would the elementtree look like? Should I just use 'config'? or
> something similar as root, and the information elements 1 through 3 as
> child elements? And should the manual edits be stored as an element
> 'edit' with various attributes (the edit itself, the time stamp,
> etc.)?

I am with Steven on the fact that XML might not necessarily be the best
choice, unless you plan to use the configuration file with other
third-party programs, in which case the fact that XML has built-in
parsing libs for nearly all languages makes life of fellow developer
easier.

For the next project of mines, I am planning to use YAML (YAML Ain't a
Markup Language). I stumbled upon this format while toying around with
the google app engine, that uses it for storing your application
configuration data. IMO, YAML has the following prominent advantages:
???1) It is easy to read and edit by humans [think "markdown"]
???2) It has solid parsing libraries for Python
???3) It is far less verbose than XML
???4) It is consistent with Python "relevant whitespaces" [indentation
is used to define data structure hierarchy]

I have not yet got to the stage of writing code that use YAML (will take
two more weeks at best for me to get to that point), but should you go
down this road, I would love to hear back from you. [As I would love to
hear from anybody else who might have experience with YAML+Python]

Some links:
- http://en.wikipedia.org/wiki/YAML [good overview of the format]
- http://www.yaml.org/ [official site... when consistency with the
format makes a website hard to browse!]
- http://pyyaml.org/wiki/PyYAMLDocumentation [documentation of the
library for Python - pure Python code // can use a C library]

An example of YAML file to give you the taste of it:
> receipt:? ???Oz-Ware Purchase Invoice
> date:? ? ? ? 2007-08-06
> 
> customer:
>? ???given:???Dorothy
>? ???family:? Gale
> 
> items:
>? ???- part_no:???A4786
>? ? ???descrip:???Water Bucket (Filled)
>? ? ???price:? ???1.47
>? ? ???quantity:? 4
>? ???- part_no:???E1628
>? ? ???descrip:???High Heeled "Ruby" Slippers
>? ? ???price:? ???100.27
>? ? ???quantity:? 1
> 
> bill-to:? &id001
>? ???street: |
>? ? ? ? ? ???123 Tornado Alley
>? ? ? ? ? ???Suite 16
>? ???city:???East Westville
>? ???state:? KS
> 
> ship-to:? *id001
> 
> specialDelivery:? >
>? ???Follow the Yellow Brick
>? ???Road to the Emerald City.
>? ???Pay no attention to the
>? ???man behind the curtain.

HTH,
Mac.


_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100727/27e7be8f/attachment-0001.html>

From grflanagan at gmail.com  Tue Jul 27 21:03:17 2010
From: grflanagan at gmail.com (Gerard Flanagan)
Date: Tue, 27 Jul 2010 20:03:17 +0100
Subject: [Tutor] nested list help
In-Reply-To: <AANLkTi=uYt+kFC=552NLED_yyL6RAUE2B8VMf+F5r_pP@mail.gmail.com>
References: <AANLkTi=uYt+kFC=552NLED_yyL6RAUE2B8VMf+F5r_pP@mail.gmail.com>
Message-ID: <i2nahl$lf7$1@dough.gmane.org>

Vikram K wrote:
> Suppose i have this nested list:
> 
>  >>> x
> [['NM100', 3, 4, 5, 6, 7], ['NM100', 10, 11, 12, 13], ['NM200', 15, 16, 17]]
>  >>> for i in x:
> ...   print i
> ...
> ['NM100', 3, 4, 5, 6, 7]
> ['NM100', 10, 11, 12, 13]
> ['NM200', 15, 16, 17]
>  >>>
> 
> how do i obtain from the above the following nested list:
> 
>  >>> z
> [['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13], ['NM200', 15, 16, 17]]
>  >>> for i in z:
> ...   print i
> ...
> ['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13]
> ['NM200', 15, 16, 17]
>  >>>
> 


z = [['NM100', 3, 4, 5, 6, 7], ['NM100', 10, 11, 12, 13], ['NM200', 15, 
16, 17]]

from itertools import groupby

# assumes that the data is already sorted by the first element as it is here
# if not then you must sort, eg. with the same function you group by:
# z.sort(key=lambda X: X[0])
# also assumes that there are no empty lists

def merge(inlist):
     for k, g in groupby(inlist, lambda X: X[0]):
         k = [k]
         for item in g:
             k.extend(item[1:])
         yield k

print list(merge(z))

[['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13], ['NM200', 15, 16, 17]]

def merge(inlist):
     for k, g in groupby(inlist, lambda X: X[0]):
         newlist = []
         for item in g:
             newlist.extend(item[1:])
         yield k, newlist

print dict(merge(z))

{'NM100': [3, 4, 5, 6, 7, 10, 11, 12, 13], 'NM200': [15, 16, 17]}


From rdmoores at gmail.com  Tue Jul 27 21:12:14 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Tue, 27 Jul 2010 12:12:14 -0700
Subject: [Tutor] need help with msvcrt.getch()
In-Reply-To: <4C4EF283.3040306@otenet.gr>
References: <AANLkTikfEWYTzmKOd1ibTe_WVca=TGzsrJgbvAv6ce8r@mail.gmail.com> 
	<4C4EF283.3040306@otenet.gr>
Message-ID: <AANLkTi=-Dq6iDpDsRPAuLb0Yb=-rKK+2E7ye69irvPwB@mail.gmail.com>

On Tue, Jul 27, 2010 at 07:51, Nick Raptis <airscorp at otenet.gr> wrote:

> On 07/27/2010 05:22 PM, Richard D. Moores wrote:
>
>> Python 3.1 on Vista.
>>
>> Please see <http://tutoree7.pastebin.com/f3TaxDBc>.
>>
>> I'm trying to recall what I used to know, thus this simple script. But 'y'
>> or 'q' do nothing. What's wrong?
>>
>> Thanks,
>>
>> Dick Moores
>>
>>
> Hi Dick!
> I'm not on Windows here so this might be a wild guess.
>
> From the documentation I gather that msvcrt can work either on binary or
> text mode.
> Perhaps you operate in the wrong one and need to switch with
> msvcrt.setmode(/)
>
> Anyway, insert some print lines to see what exactly is it that /getch()
> gets and debug from there
>
> Nick
>

I replied to only to Nick, by mistake, and after some private back and
forth, he came up with another way to avoid having to use those b's, as in
b'y' and b'q'. It works! See <http://tutoree7.pastebin.com/6pdN1MvW>,
highlighted line 11.

Dick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100727/63c77f92/attachment.html>

From kevin at digikev.co.uk  Tue Jul 27 21:02:33 2010
From: kevin at digikev.co.uk (Kevin Rapley)
Date: Tue, 27 Jul 2010 20:02:33 +0100
Subject: [Tutor] Running .py files in shell
Message-ID: <4C4F2D49.2030201@digikev.co.uk>

  Hello all, I am new to programming and have opted to learn Python as I 
hear it is a good first language. I am currently going through the 
exercises in 'How to Think Like a Computer Scientist: Learning with 
Python 2nd Edition'.

I am running Mac OSX v10.6.4 Snow Leopard
I am running Python 2.6.1

I have a couple of questions:

1. How do I execute .py files in the command line shell? I have my files 
in /Users/Kevin/python-exercises/ and am opening python in shell from 
that directory

2. How do I install GASP which is referenced in chapter 4? The 
instructions in this book are not complete. I have researched and found 
a reference on Stack Overflow which is contributed to by GASP programmers
http://stackoverflow.com/questions/1024862/how-do-i-install-gasp-for-python-2-6-2-on-a-mac

I have MacPorts installed and have attempted to install PyObjC, which is 
referenced as a prerequisite to PyGame and GASP. I get the following 
error when attempting to install PyObjC:

sudo port install py-pyobjc
Password:
--->  Computing dependencies for py-pyobjc
--->  Fetching py-pyobjc
Error: Target org.macports.fetch returned: PyObjC 1.4 is for Mac OS X 
10.4 and lower. On 10.5, use py-pyobjc2 instead.
Log for py-pyobjc is at: 
/opt/local/var/macports/logs/_opt_local_var_macports_sources_rsync.macports.org_release_ports_python_py-pyobjc/main.log
Error: Status 1 encountered during processing.

It says to use py-objc2 instead, so I do so and get this error:

sudo port install py-pyobjc2
Error: Target org.macports.activate returned: Image error: 
/opt/local/lib/python2.4/site-packages/modulegraph/__init__.py is being 
used by the active py-modulegraph port.  Please deactivate this port 
first, or use 'port -f activate py-modulegraph-devel' to force the 
activation.
Log for py-modulegraph-devel is at: 
/opt/local/var/macports/logs/_opt_local_var_macports_sources_rsync.macports.org_release_ports_python_py-modulegraph-devel/main.log
Error: The following dependencies failed to build: py-py2app-devel 
py-modulegraph-devel
Error: Status 1 encountered during processing.
To report a bug, see <http://guide.macports.org/#project.tickets>

I attempted to correct the issue by entering the following:

port -f activate py-modulegraph-devel

But it returned this error:

Warning: Failed to open Portfile from registry for py-modulegraph-devel 
@0.7.2_0
--->  Activating py-modulegraph-devel
Error: port activate failed: sqlite error: attempt to write a readonly 
database (8)

This is as far as I have got with resolving this issue so far. All help 
and guidance will be greatly appreciated.

Kevin Rapley

From marris1031 at gmail.com  Tue Jul 27 22:11:18 2010
From: marris1031 at gmail.com (Mary Morris)
Date: Tue, 27 Jul 2010 14:11:18 -0600
Subject: [Tutor] Decorator listing
Message-ID: <AANLkTin6VYbPY_Jv6OKZsuF0hZm3T4Ps9WamhVmnWZ1A@mail.gmail.com>

I'm writing a program with python that compiles a list of decorators from my
company's source code.  I'm new to python and need help with the following:
I'm trying to make the program find ".com" in any lines and not include them
in the list of decorators that gets returned.  THis is because I had the
program look for the @ symbol to find the decorators and it returned email
addresses in the list.  What I was thinking was to do something like this:
k = candidate_line.find(".com")
if k != -1:
     candidate_line != candidate_line

The problem is that I know this won't work because ".com" can't be in the
last slot of the candidate line...  So far the part of my code that needs to
be changed looks like this...


      #parse out the names of the decorators from those lines
        return_decorators= []
        for ele in subset_lines:
                candidate_line, line_number = ele
                candidate_line = candidate_line.strip()
                i = candidate_line.find("(")
                j = candidate_line.find("#")
                k = candidate_line.find(".com")
                #if () is in the last spot
                if i == -1:
                        #if () is in the last spot and the decorator is in a
comment
                        if j == 0:
                                #get rid of ( and #
                                candidate_line = candidate_line[2:i]
                        #if () is in the last spot and the decorator is not
in a comment
                        elif j != 0:
                                candidate_line = candidate_line[1:i]
                #if there are not ()'s in the last spot
                elif i != -1:
                        #if there are not ()'s, but the decorator is in a
comment
                        if j == 0:
                                candidate_line = candidate_line[2:]
                        #if there are not ()'s and the decorator isn't in a
comment
                        elif j != 0:
                                candidate_line = candidate_line[1:]
                elif k in candidate_line:
                        candidate_line != candidate_line
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100727/07683823/attachment.html>

From steve at pearwood.info  Wed Jul 28 00:08:56 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 28 Jul 2010 08:08:56 +1000
Subject: [Tutor] lambda vs list comp
In-Reply-To: <AANLkTiniGBidmezwO4rSwy0=mttU5hBF9DRQVhtp9dLO@mail.gmail.com>
References: <AANLkTiniGBidmezwO4rSwy0=mttU5hBF9DRQVhtp9dLO@mail.gmail.com>
Message-ID: <201007280808.56624.steve@pearwood.info>

On Wed, 28 Jul 2010 02:44:02 am Jon Crump wrote:
> Just as a matter of curiosity piqued by having to understand someone
> else's code. Is the difference here just a matter of style, or is one
> better somehow than the other?

Remember that list comprehensions didn't exist until a few years ago, so 
older code will use map() to implement the same functionality.

> >>> l
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Using lowercase L on its own as a name is not recommended, because it 
looks too similar to 1 and hence difficult to read. For example, the 
next line reads to me like "blah blah for x in ONE", I do a 
double-take, read it again, and realise it's actually L.


> >>> ','.join([str(x) for x in l])
> '0,1,2,3,4,5,6,7,8,9,10'

This would be the preferred (or "Pythonic") way to do this for most 
people these days. That, or a generator expression:

','.join(str(x) for x in l)

Using the list comp form is a micro-optimization over the generator 
expression form (it allows join to allocate the memory needed ahead of 
time, since it has a known size).


> >>> ','.join(map(lambda x:str(x), l))
>
> '0,1,2,3,4,5,6,7,8,9,10'


That is a line of code written by somebody who doesn't quite get it.

There seems to be something about map and lambda that leads so many 
people into making that silly mistake when they wouldn't make it 
elsewhere. You (generic you, not you personally) almost certainly 
wouldn't write:

def mystr(x):
    return str(x)

n = 42
s = mystr(n)


instead of the more obvious s = str(n). But bring map() into it, and 
people make that exact mistake, writing:

map(lambda x: str(x), L)

instead of the simpler and faster:

map(str, L)



-- 
Steven D'Aprano

From emile at fenx.com  Wed Jul 28 00:13:06 2010
From: emile at fenx.com (Emile van Sebille)
Date: Tue, 27 Jul 2010 15:13:06 -0700
Subject: [Tutor] Decorator listing
In-Reply-To: <AANLkTin6VYbPY_Jv6OKZsuF0hZm3T4Ps9WamhVmnWZ1A@mail.gmail.com>
References: <AANLkTin6VYbPY_Jv6OKZsuF0hZm3T4Ps9WamhVmnWZ1A@mail.gmail.com>
Message-ID: <i2nlll$tgk$1@dough.gmane.org>

On 7/27/2010 1:11 PM Mary Morris said...
> I'm writing a program with python that compiles a list of decorators from my
> company's source code.  I'm new to python and need help with the following:
> I'm trying to make the program find ".com" in any lines and not include them
> in the list of decorators that gets returned.  THis is because I had the
> program look for the @ symbol to find the decorators and it returned email
> addresses in the list.

You can probably sidestep this issue by looking for the @ symbol in the 
first non-whitespace position in the line, rather than in any position 
of the line.

IE, instead of something like:

   if "@" in line:

...try something more like:

   if line.strip().startswith("@"):


This way you won't pick up the email addresses at all, and won't 
subsequently need to filter them out of your results set.

HTH,

Emile




From zuxoxus at gmail.com  Wed Jul 28 00:20:32 2010
From: zuxoxus at gmail.com (ZUXOXUS)
Date: Wed, 28 Jul 2010 00:20:32 +0200
Subject: [Tutor] Calculating and returning possible combinations of elements
	from a given set
Message-ID: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>

Hi all pythoners

I've got a probably easy to answer question.

Say I've got a collections of strings, e.g.: 'man', 'bat', 'super', 'ultra'.

They are in a list, or in a sequence or whatever, say a bag of words

And now I want to know how many couples I can do with them, and I want the
program to show me the actual couples: 'manman', 'manbat', 'mansuper',
'manultra', 'batbat', 'batman', 'batsuper', etc.

But hey, why building up new words from just two strings? I also want to
know the possible combinations of three words, four words, and perhaps, why
not, five words.

So, is it easy to do?

Sorry, I'm new in programing, and am probably far from being a math-master

I'm clueless, I think probably the code have some FOR I IN SEQUENCE... but
then what? I don't know how to say: take every element and paste it to
another one from the bag, and with another one, and with another one,...

If it's too complex, I dont need the whole code recipe, just need some
clues, or perhaps a useful link

Thank you very much in advance!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/87aff37e/attachment.html>

From steve at pearwood.info  Wed Jul 28 00:21:38 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 28 Jul 2010 08:21:38 +1000
Subject: [Tutor] Decorator listing
In-Reply-To: <AANLkTin6VYbPY_Jv6OKZsuF0hZm3T4Ps9WamhVmnWZ1A@mail.gmail.com>
References: <AANLkTin6VYbPY_Jv6OKZsuF0hZm3T4Ps9WamhVmnWZ1A@mail.gmail.com>
Message-ID: <201007280821.38436.steve@pearwood.info>

Hello Mary,

On Wed, 28 Jul 2010 06:11:18 am Mary Morris wrote:
> I'm writing a program with python that compiles a list of decorators
> from my company's source code.  I'm new to python and need help with
> the following: I'm trying to make the program find ".com" in any 
> lines and not include them in the list of decorators that gets
> returned.  

What's special about .com? What about email addresses that end 
in .org, .co.uk, .net. .gov.au, .cx, .info, .biz, or any one of a 
million million other email addresses?


> THis is because I had the program look for the @ symbol to 
> find the decorators and it returned email addresses in the list. 

With respect Mary, I replied to your last question about this on 
Saturday. Did you read that? Was it useful? Did you have questions? I 
think the approach you are taking is the wrong approach and is doomed 
to failure. I fear that you are taking a problem that can be solved 
very simply, and making it much, much, much more complicated than it 
needs to be.

Please read my email sent in response to your last question about this, 
and good luck!



-- 
Steven D'Aprano

From airscorp at otenet.gr  Wed Jul 28 00:31:39 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Wed, 28 Jul 2010 01:31:39 +0300
Subject: [Tutor] Calculating and returning possible combinations of
 elements from a given set
In-Reply-To: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>
References: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>
Message-ID: <4C4F5E4B.5050001@otenet.gr>

On 07/28/2010 01:20 AM, ZUXOXUS wrote:
> Hi all pythoners
>
> I've got a probably easy to answer question.
>
> Say I've got a collections of strings, e.g.: 'man', 'bat', 'super', 
> 'ultra'.
>
> They are in a list, or in a sequence or whatever, say a bag of words
>
> And now I want to know how many couples I can do with them, and I want 
> the program to show me the actual couples: 'manman', 'manbat', 
> 'mansuper', 'manultra', 'batbat', 'batman', 'batsuper', etc.
>
> But hey, why building up new words from just two strings? I also want 
> to know the possible combinations of three words, four words, and 
> perhaps, why not, five words.
>
> So, is it easy to do?
>
> Sorry, I'm new in programing, and am probably far from being a math-master
>
> I'm clueless, I think probably the code have some FOR I IN SEQUENCE... 
> but then what? I don't know how to say: take every element and paste 
> it to another one from the bag, and with another one, and with another 
> one,...
>
> If it's too complex, I dont need the whole code recipe, just need some 
> clues, or perhaps a useful link
>
> Thank you very much in advance!
>

Take a look in the itertools module 
http://docs.python.org/library/itertools.html
Check the section "*Combinatoric generators:" (website doesn't have an 
anchor link for that, search around a bit)

Nick
*

From breamoreboy at yahoo.co.uk  Wed Jul 28 00:31:52 2010
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 27 Jul 2010 23:31:52 +0100
Subject: [Tutor] Calculating and returning possible combinations of
 elements from a given set
In-Reply-To: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>
References: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>
Message-ID: <i2nmot$1a1$1@dough.gmane.org>

On 27/07/2010 23:20, ZUXOXUS wrote:
> Hi all pythoners
>
> I've got a probably easy to answer question.
>
> Say I've got a collections of strings, e.g.: 'man', 'bat', 'super', 'ultra'.
>
> They are in a list, or in a sequence or whatever, say a bag of words
>
> And now I want to know how many couples I can do with them, and I want the
> program to show me the actual couples: 'manman', 'manbat', 'mansuper',
> 'manultra', 'batbat', 'batman', 'batsuper', etc.
>
> But hey, why building up new words from just two strings? I also want to
> know the possible combinations of three words, four words, and perhaps, why
> not, five words.
>
> So, is it easy to do?
>
> Sorry, I'm new in programing, and am probably far from being a math-master
>
> I'm clueless, I think probably the code have some FOR I IN SEQUENCE... but
> then what? I don't know how to say: take every element and paste it to
> another one from the bag, and with another one, and with another one,...
>
> If it's too complex, I dont need the whole code recipe, just need some
> clues, or perhaps a useful link
>
> Thank you very much in advance!
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

The lazy way.
http://docs.python.org/library/itertools.html
Look for combinations().

HTH.

Mark Lawrence.



From quasipedia at gmail.com  Wed Jul 28 00:53:02 2010
From: quasipedia at gmail.com (Mac Ryan)
Date: Wed, 28 Jul 2010 00:53:02 +0200
Subject: [Tutor] Calculating and returning possible combinations of
 elements from a given set
In-Reply-To: <i2nmot$1a1$1@dough.gmane.org>
References: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>
	<i2nmot$1a1$1@dough.gmane.org>
Message-ID: <1280271182.12064.28.camel@jabbar>

On Tue, 2010-07-27 at 23:31 +0100, Mark Lawrence wrote:
> On 27/07/2010 23:20, ZUXOXUS wrote:
> > Hi all pythoners
> >
> > I've got a probably easy to answer question.
> >
> > Say I've got a collections of strings, e.g.: 'man', 'bat', 'super', 'ultra'.
> >
> > They are in a list, or in a sequence or whatever, say a bag of words
> >
> > And now I want to know how many couples I can do with them, and I want the
> > program to show me the actual couples: 'manman', 'manbat', 'mansuper',
> > 'manultra', 'batbat', 'batman', 'batsuper', etc.
> >
> > But hey, why building up new words from just two strings? I also want to
> > know the possible combinations of three words, four words, and perhaps, why
> > not, five words.
> >
> > So, is it easy to do?
> >
> > Sorry, I'm new in programing, and am probably far from being a math-master
> >
> > I'm clueless, I think probably the code have some FOR I IN SEQUENCE... but
> > then what? I don't know how to say: take every element and paste it to
> > another one from the bag, and with another one, and with another one,...
> >
> > If it's too complex, I dont need the whole code recipe, just need some
> > clues, or perhaps a useful link
> >
> > Thank you very much in advance!
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> 
> The lazy way.
> http://docs.python.org/library/itertools.html
> Look for combinations().

>From the examples listed by the OP (see: "manbat", "batman") I actually
believe he is looking for the cartesian product.

The syntax should therefore be (DISCLAIMER: I am going by memory without
having the possibility of testing right now):

import itertools
for prod in itertools.product(my_list_of_words, 2):
    print prod

(The two as second parameter tells that you are wishing to have a
bi-dimensional product, with both axis having the same list of words.
See docs for more info)


From zuxoxus at gmail.com  Wed Jul 28 00:55:47 2010
From: zuxoxus at gmail.com (ZUXOXUS)
Date: Wed, 28 Jul 2010 00:55:47 +0200
Subject: [Tutor] Calculating and returning possible combinations of
	elements from a given set
In-Reply-To: <i2nmot$1a1$1@dough.gmane.org>
References: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>
	<i2nmot$1a1$1@dough.gmane.org>
Message-ID: <AANLkTikTM9GGOZcKmtQ-yOgxh1cs7tps7mpvAsgc752C@mail.gmail.com>

Sharp thanks, but:

I try to reproduce the example from the table, but:

>>> import itertools
>>> combinations('ABC', 2)
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    combinations('ABC', 2)
NameError: name 'combinations' is not defined
>>>

If im not mistaken, it should return AB, AC, BA, etc.

I'm using Python 3.1


2010/7/28 Mark Lawrence <breamoreboy at yahoo.co.uk>

> On 27/07/2010 23:20, ZUXOXUS wrote:
>
>> Hi all pythoners
>>
>> I've got a probably easy to answer question.
>>
>> Say I've got a collections of strings, e.g.: 'man', 'bat', 'super',
>> 'ultra'.
>>
>> They are in a list, or in a sequence or whatever, say a bag of words
>>
>> And now I want to know how many couples I can do with them, and I want the
>> program to show me the actual couples: 'manman', 'manbat', 'mansuper',
>> 'manultra', 'batbat', 'batman', 'batsuper', etc.
>>
>> But hey, why building up new words from just two strings? I also want to
>> know the possible combinations of three words, four words, and perhaps,
>> why
>> not, five words.
>>
>> So, is it easy to do?
>>
>> Sorry, I'm new in programing, and am probably far from being a math-master
>>
>> I'm clueless, I think probably the code have some FOR I IN SEQUENCE... but
>> then what? I don't know how to say: take every element and paste it to
>> another one from the bag, and with another one, and with another one,...
>>
>> If it's too complex, I dont need the whole code recipe, just need some
>> clues, or perhaps a useful link
>>
>> Thank you very much in advance!
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
> The lazy way.
>
> http://docs.python.org/library/itertools.html
> Look for combinations().
>
> HTH.
>
> Mark Lawrence.
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/01a73e47/attachment.html>

From alan.gauld at btinternet.com  Wed Jul 28 01:01:19 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 28 Jul 2010 00:01:19 +0100
Subject: [Tutor] Running .py files in shell
References: <4C4F2D49.2030201@digikev.co.uk>
Message-ID: <i2nofs$65g$1@dough.gmane.org>

"Kevin Rapley" <kevin at digikev.co.uk> wrote

> I am running Mac OSX v10.6.4 Snow Leopard
> I am running Python 2.6.1

In general get the MacPython distributions of Python etc, they usually
install easier (ie from the GUI) than the "Unix" based versions.

> 1. How do I execute .py files in the command line shell? I have my 
> files in /Users/Kevin/python-exercises/ and am opening python in 
> shell from that directory

There are numerous ways, especially in MacOS.
The simplest way is to put a "shebang" line at the top of your script
and then make them executable:

$ cat > myscript.py
#! /bin/env python
# the above line must be the first line in your file and tells the
# shell where to find python
# rest of your code follows.....

Then use chmod +x to make it executable

$ chmod +x myscript.py

Now you can run it:

$ myscript.py

Alternatively you can just call python explicitly:

$ python myscript.py

You can do other things with file associations and
MacOS bundles/packages etc but unless its a major app
that you use a lot the techniques above are easier.

> 2. How do I install GASP which is referenced in chapter 4?

Can't help you there, sorry...

> I have MacPorts installed and have attempted to install PyObjC, 
> which is referenced as a prerequisite to PyGame and GASP. I get the 
> following error when attempting to install PyObjC:

Check the MacPython web site, I'm sure I used an install
package when I played with PyObjC...

HTH,


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



From zuxoxus at gmail.com  Wed Jul 28 01:01:51 2010
From: zuxoxus at gmail.com (ZUXOXUS)
Date: Wed, 28 Jul 2010 01:01:51 +0200
Subject: [Tutor] Calculating and returning possible combinations of
	elements from a given set
In-Reply-To: <AANLkTikTM9GGOZcKmtQ-yOgxh1cs7tps7mpvAsgc752C@mail.gmail.com>
References: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>
	<i2nmot$1a1$1@dough.gmane.org>
	<AANLkTikTM9GGOZcKmtQ-yOgxh1cs7tps7mpvAsgc752C@mail.gmail.com>
Message-ID: <AANLkTimPRRT+8vsiXsNWnwhnAcEkmoYZyoXhj+TPaQ_C@mail.gmail.com>

Mac,

this is what I get:

>>> for prod in itertools.product('ABC', 2):
print(prod)

Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    for prod in itertools.product('ABC', 2):
TypeError: 'int' object is not iterable


hmm, what might be that 'int' object? 2?


2010/7/28 ZUXOXUS <zuxoxus at gmail.com>

> Sharp thanks, but:
>
> I try to reproduce the example from the table, but:
>
> >>> import itertools
> >>> combinations('ABC', 2)
> Traceback (most recent call last):
>   File "<pyshell#27>", line 1, in <module>
>     combinations('ABC', 2)
> NameError: name 'combinations' is not defined
> >>>
>
> If im not mistaken, it should return AB, AC, BA, etc.
>
> I'm using Python 3.1
>
>
> 2010/7/28 Mark Lawrence <breamoreboy at yahoo.co.uk>
>
> On 27/07/2010 23:20, ZUXOXUS wrote:
>>
>>> Hi all pythoners
>>>
>>> I've got a probably easy to answer question.
>>>
>>> Say I've got a collections of strings, e.g.: 'man', 'bat', 'super',
>>> 'ultra'.
>>>
>>> They are in a list, or in a sequence or whatever, say a bag of words
>>>
>>> And now I want to know how many couples I can do with them, and I want
>>> the
>>> program to show me the actual couples: 'manman', 'manbat', 'mansuper',
>>> 'manultra', 'batbat', 'batman', 'batsuper', etc.
>>>
>>> But hey, why building up new words from just two strings? I also want to
>>> know the possible combinations of three words, four words, and perhaps,
>>> why
>>> not, five words.
>>>
>>> So, is it easy to do?
>>>
>>> Sorry, I'm new in programing, and am probably far from being a
>>> math-master
>>>
>>> I'm clueless, I think probably the code have some FOR I IN SEQUENCE...
>>> but
>>> then what? I don't know how to say: take every element and paste it to
>>> another one from the bag, and with another one, and with another one,...
>>>
>>> If it's too complex, I dont need the whole code recipe, just need some
>>> clues, or perhaps a useful link
>>>
>>> Thank you very much in advance!
>>>
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>
>> The lazy way.
>>
>> http://docs.python.org/library/itertools.html
>> Look for combinations().
>>
>> HTH.
>>
>> Mark Lawrence.
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/ab1817ee/attachment.html>

From zuxoxus at gmail.com  Wed Jul 28 01:07:28 2010
From: zuxoxus at gmail.com (ZUXOXUS)
Date: Wed, 28 Jul 2010 01:07:28 +0200
Subject: [Tutor] Calculating and returning possible combinations of
	elements from a given set
In-Reply-To: <AANLkTimPRRT+8vsiXsNWnwhnAcEkmoYZyoXhj+TPaQ_C@mail.gmail.com>
References: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>
	<i2nmot$1a1$1@dough.gmane.org>
	<AANLkTikTM9GGOZcKmtQ-yOgxh1cs7tps7mpvAsgc752C@mail.gmail.com>
	<AANLkTimPRRT+8vsiXsNWnwhnAcEkmoYZyoXhj+TPaQ_C@mail.gmail.com>
Message-ID: <AANLkTimpNHKs=U89NuEQd5OsEitxTh4VYLRfOzG+DddA@mail.gmail.com>

Oh, I think i got it:

>>> for prod in itertools.product('ABC', 'ABC'):
print(prod)

('A', 'A')
('A', 'B')
('A', 'C')
('B', 'A')
('B', 'B')
('B', 'C')
('C', 'A')
('C', 'B')
('C', 'C')

Thank you very much!!

2010/7/28 ZUXOXUS <zuxoxus at gmail.com>

> Mac,
>
> this is what I get:
>
> >>> for prod in itertools.product('ABC', 2):
> print(prod)
>
> Traceback (most recent call last):
>   File "<pyshell#34>", line 1, in <module>
>     for prod in itertools.product('ABC', 2):
> TypeError: 'int' object is not iterable
>
>
> hmm, what might be that 'int' object? 2?
>
>
> 2010/7/28 ZUXOXUS <zuxoxus at gmail.com>
>
> Sharp thanks, but:
>>
>> I try to reproduce the example from the table, but:
>>
>> >>> import itertools
>> >>> combinations('ABC', 2)
>> Traceback (most recent call last):
>>   File "<pyshell#27>", line 1, in <module>
>>     combinations('ABC', 2)
>> NameError: name 'combinations' is not defined
>> >>>
>>
>> If im not mistaken, it should return AB, AC, BA, etc.
>>
>> I'm using Python 3.1
>>
>>
>> 2010/7/28 Mark Lawrence <breamoreboy at yahoo.co.uk>
>>
>> On 27/07/2010 23:20, ZUXOXUS wrote:
>>>
>>>> Hi all pythoners
>>>>
>>>> I've got a probably easy to answer question.
>>>>
>>>> Say I've got a collections of strings, e.g.: 'man', 'bat', 'super',
>>>> 'ultra'.
>>>>
>>>> They are in a list, or in a sequence or whatever, say a bag of words
>>>>
>>>> And now I want to know how many couples I can do with them, and I want
>>>> the
>>>> program to show me the actual couples: 'manman', 'manbat', 'mansuper',
>>>> 'manultra', 'batbat', 'batman', 'batsuper', etc.
>>>>
>>>> But hey, why building up new words from just two strings? I also want to
>>>> know the possible combinations of three words, four words, and perhaps,
>>>> why
>>>> not, five words.
>>>>
>>>> So, is it easy to do?
>>>>
>>>> Sorry, I'm new in programing, and am probably far from being a
>>>> math-master
>>>>
>>>> I'm clueless, I think probably the code have some FOR I IN SEQUENCE...
>>>> but
>>>> then what? I don't know how to say: take every element and paste it to
>>>> another one from the bag, and with another one, and with another one,...
>>>>
>>>> If it's too complex, I dont need the whole code recipe, just need some
>>>> clues, or perhaps a useful link
>>>>
>>>> Thank you very much in advance!
>>>>
>>>> _______________________________________________
>>>> Tutor maillist  -  Tutor at python.org
>>>> To unsubscribe or change subscription options:
>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>
>>>
>>> The lazy way.
>>>
>>> http://docs.python.org/library/itertools.html
>>> Look for combinations().
>>>
>>> HTH.
>>>
>>> Mark Lawrence.
>>>
>>>
>>>
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/4c449657/attachment-0001.html>

From davea at ieee.org  Wed Jul 28 04:11:25 2010
From: davea at ieee.org (Dave Angel)
Date: Tue, 27 Jul 2010 22:11:25 -0400
Subject: [Tutor] Calculating and returning possible combinations
 of	elements from a given set
In-Reply-To: <AANLkTimpNHKs=U89NuEQd5OsEitxTh4VYLRfOzG+DddA@mail.gmail.com>
References: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>	<i2nmot$1a1$1@dough.gmane.org>	<AANLkTikTM9GGOZcKmtQ-yOgxh1cs7tps7mpvAsgc752C@mail.gmail.com>	<AANLkTimPRRT+8vsiXsNWnwhnAcEkmoYZyoXhj+TPaQ_C@mail.gmail.com>
	<AANLkTimpNHKs=U89NuEQd5OsEitxTh4VYLRfOzG+DddA@mail.gmail.com>
Message-ID: <4C4F91CD.3020902@ieee.org>



ZUXOXUS wrote:
> Oh, I think i got it:
>
>   
>>>> for prod in itertools.product('ABC', 'ABC'):
>>>>         
> print(prod)
>
> ('A', 'A')
> ('A', 'B')
> ('A', 'C')
> ('B', 'A')
> ('B', 'B')
> ('B', 'C')
> ('C', 'A')
> ('C', 'B')
> ('C', 'C')
>
> Thank you very much!!
>
> 2010/7/28 ZUXOXUS <zuxoxus at gmail.com>
>   
>
You're top-posting, which loses all the context. In this forum, put your 
comments after whatever lines you're quoting.

Your latest version gets the product of two.  But if you want an 
arbitrary number, instead of repeating the iterable ('ABC' in your 
case), you can use a repeat count.  That's presumably what you were 
trying to do in your earlier incantation.  But you forgot the 'repeat' 
keyword:

for prod in itertools.product('ABC', repeat=4):
    xxxx

will give you all the four-tuples.

DaveA





From ashley at qxhp.com  Wed Jul 28 05:38:52 2010
From: ashley at qxhp.com (ashley at qxhp.com)
Date: Tue, 27 Jul 2010 20:38:52 -0700
Subject: [Tutor] subprocess output
Message-ID: <7f9341edff70d4d84c3241fac110d756.squirrel@webmail.qxhp.com>

I'm using Python 2.6.5 and I've got a challenge with the subprocess
module. I'd like the output to be stored in a variable, and not sent to
the stdout. The relevant lines as they are now:

#!/usr/bin/env python
import subprocess
import sys

dom = sys.argv[1]
switch = sys.argv [2]
answer = subprocess.call("whois " + dom, shell=True)

Execute the above (whatever.py -example.com -a1) prints the entire WHOIS
output, but I just want it saved to the variable 'answer', nothing more.

Changing 'shell=True' to 'shell=False' raises an exception and removing
the 'shell=' altogether is troublesome as well.

Thoughts on how I can accomplish this?

Thanks!



From sander.sweers at gmail.com  Wed Jul 28 09:01:44 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Wed, 28 Jul 2010 09:01:44 +0200
Subject: [Tutor] subprocess output
In-Reply-To: <7f9341edff70d4d84c3241fac110d756.squirrel@webmail.qxhp.com>
References: <7f9341edff70d4d84c3241fac110d756.squirrel@webmail.qxhp.com>
Message-ID: <1280300504.12617.2.camel@Nokia-N900>

----- Original message -----
> I'm using Python 2.6.5 and I've got a challenge with the subprocess
> module. I'd like the output to be stored in a variable, and not sent to
> the stdout. The relevant lines as they are now:

Go to google, enter "pymotw subprocess" and hit I am feeling lucky ;-)

greets
Sander


From evert.rol at gmail.com  Wed Jul 28 09:09:37 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 28 Jul 2010 09:09:37 +0200
Subject: [Tutor] subprocess output
In-Reply-To: <7f9341edff70d4d84c3241fac110d756.squirrel@webmail.qxhp.com>
References: <7f9341edff70d4d84c3241fac110d756.squirrel@webmail.qxhp.com>
Message-ID: <3B6E5537-6EE4-46B1-9DD2-3E892475D340@gmail.com>

> #!/usr/bin/env python
> import subprocess
> import sys
> 
> dom = sys.argv[1]
> switch = sys.argv [2]
> answer = subprocess.call("whois " + dom, shell=True)
> 
> Execute the above (whatever.py -example.com -a1) prints the entire WHOIS
> output, but I just want it saved to the variable 'answer', nothing more.

create a subprocess.Popen object instead, and use communicate().
Use subprocess.PIPE for the stdout and stderr arguments (and use a list for the executable + arguments: ["whois", dom], leaving out the shell argument).
Read the library docs: see example 17.1.3.2.


> Changing 'shell=True' to 'shell=False' raises an exception and removing
> the 'shell=' altogether is troublesome as well.

shell=False is the default


From kevin at digikev.co.uk  Wed Jul 28 08:39:23 2010
From: kevin at digikev.co.uk (Kevin Rapley)
Date: Wed, 28 Jul 2010 07:39:23 +0100
Subject: [Tutor] Running .py files in shell
In-Reply-To: <mailman.5635.1280272049.1671.tutor@python.org>
References: <mailman.5635.1280272049.1671.tutor@python.org>
Message-ID: <4C4FD09B.6090300@digikev.co.uk>


>> I am running Mac OSX v10.6.4 Snow Leopard
>> I am running Python 2.6.1
> In general get the MacPython distributions of Python etc, they usually
> install easier (ie from the GUI) than the "Unix" based versions.
Okay, thanks. I will look into that.
>> 1. How do I execute .py files in the command line shell? I have my
>> files in /Users/Kevin/python-exercises/ and am opening python in
>> shell from that directory
> There are numerous ways, especially in MacOS.
> The simplest way is to put a "shebang" line at the top of your script
> and then make them executable:
>
> $ cat>  myscript.py
What is the significance of this and how do I use it? I guess this is a 
command to add in to Shell, however when I use this I get the following 
error:

 >>> cat > tryme1.py
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'cat' is not defined
> #! /bin/env python
With my configuration, I am guessing I need to change this snippet to:

#! /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin python
> # the above line must be the first line in your file and tells the
> # shell where to find python
> # rest of your code follows.....
>
> Then use chmod +x to make it executable
>
> $ chmod +x myscript.py
When I try to run this with one of my files I get the following error:

 >>> chmod +x tryme1.py
   File "<stdin>", line 1
     chmod +x tryme1.py
                   ^
SyntaxError: invalid syntax
> Now you can run it:
>
> $ myscript.py
>
> Alternatively you can just call python explicitly:
>
> $ python myscript.py
I get a syntax error doing this too:

 >>> python tryme1.py
   File "<stdin>", line 1
     python tryme1.py
                 ^
SyntaxError: invalid syntax

From smokefloat at gmail.com  Wed Jul 28 10:05:19 2010
From: smokefloat at gmail.com (David Hutto)
Date: Wed, 28 Jul 2010 04:05:19 -0400
Subject: [Tutor] Running .py files in shell
In-Reply-To: <4C4FD09B.6090300@digikev.co.uk>
References: <mailman.5635.1280272049.1671.tutor@python.org>
	<4C4FD09B.6090300@digikev.co.uk>
Message-ID: <AANLkTi==rru74kVwGskvt9HiXFazYtTKbYc8bEPRJanQ@mail.gmail.com>

On Wed, Jul 28, 2010 at 2:39 AM, Kevin Rapley <kevin at digikev.co.uk> wrote:
>
>>> I am running Mac OSX v10.6.4 Snow Leopard
>>> I am running Python 2.6.1
>>
>> In general get the MacPython distributions of Python etc, they usually
>> install easier (ie from the GUI) than the "Unix" based versions.
>
> Okay, thanks. I will look into that.
>>>
>>> 1. How do I execute .py files in the command line shell? I have my
>>> files in /Users/Kevin/python-exercises/ and am opening python in
>>> shell from that directory
>>
>> There are numerous ways, especially in MacOS.
>> The simplest way is to put a "shebang" line at the top of your script
>> and then make them executable:
>>
>> $ cat> ?myscript.py
>
> What is the significance of this and how do I use it? I guess this is a
> command to add in to Shell, however when I use this I get the following
> error:
>
>>>> cat > tryme1.py
> Traceback (most recent call last):
> ?File "<stdin>", line 1, in <module>
> NameError: name 'cat' is not defined
>>
>> #! /bin/env python
>
> With my configuration, I am guessing I need to change this snippet to:
>
> #! /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin python
>>
>> # the above line must be the first line in your file and tells the
>> # shell where to find python
>> # rest of your code follows.....
>>
>> Then use chmod +x to make it executable
>>
>> $ chmod +x myscript.py
>
> When I try to run this with one of my files I get the following error:
>
>>>> chmod +x tryme1.py
> ?File "<stdin>", line 1
> ? ?chmod +x tryme1.py
> ? ? ? ? ? ? ? ? ?^
> SyntaxError: invalid syntax
>>
>> Now you can run it:
>>
>> $ myscript.py
>>
>> Alternatively you can just call python explicitly:
>>
>> $ python myscript.py
>
> I get a syntax error doing this too:
>
>>>> python tryme1.py
> ?File "<stdin>", line 1
> ? ?python tryme1.py
> ? ? ? ? ? ? ? ?^
> SyntaxError: invalid syntax
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

It looks like you're trying to type it into the python prompt, when
you should be trying to type it into the shell command prompt. You can
import tryme1.py in the python shell/interpreter, but you python
tryme.py from the shell

From smokefloat at gmail.com  Wed Jul 28 11:41:48 2010
From: smokefloat at gmail.com (David Hutto)
Date: Wed, 28 Jul 2010 05:41:48 -0400
Subject: [Tutor] Order Of Operations Question
Message-ID: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com>

>From a practice exercise in Building Skills In Python page 64 I'm
working on How Much Does The Atmosphere Weigh? Part 1:
To check it states that the answer should be app. 10**18kg However,
and I've checked to make sure that the math I've layed out matches up
with the texts, I get 5.07360705863e+20

In the code I have broken the order of operations down to more
parenthetical, and tried outright, but see nothing obvious about how
it's strung together. If anyone has had a similar experience with the
problem given, or see anything blatantly obvious I've done wrong with
the ordering of operations. I tried to include as much of the
problem(formulas are just above variables they're used in) as comments
as possible.

import math
def atmosphereWeight():
    pi = math.pi
    """Air Pressure (at sea level) P0. This is the long-term average.
    P0 = 1.01325 ? 10**5"""
    airPressCLevl = 1.01325*(10**5)
    gravity = 9.82
    """We can use g to get the kg of mass from the force of air
pressure P0. Apply the acceleration of gravity
    (in m/sec2) to the air pressure (in kg ? m/sec2). This result is
mass of the atmosphere in kilograms per
    square meter (kg/m2).
    Mm2 = P0 ? g"""
    masAtmoInKgPerSqM = airPressCLevl * gravity
    """Given the mass of air per square meter, we need to know how
many square meters of surface to apply
    this mass to. Radius of Earth R in meters, m. This is an average
radius; our planet isn?t a perfect sphere.
    R = 6.37 ? 10"""
    avgRadiusEarth = 6.37 * (10**6)
    """The area of a Sphere.
    A = 4?r2"""
    areaSphere = 4 * pi * (avgRadiusEarth**2)
    """Mass of atmosphere (in Kg) is the weight per square meter,
times the number of square meters
    Ma = P0 ? g ? A"""
    masEarthAtmoInKgPerSqM = airPressCLevl * gravity * areaSphere
    print(masEarthAtmoInKgPerSqM)

atmosphereWeight()


TIA,
David

From zuxoxus at gmail.com  Wed Jul 28 12:10:36 2010
From: zuxoxus at gmail.com (ZUXOXUS)
Date: Wed, 28 Jul 2010 12:10:36 +0200
Subject: [Tutor] Calculating and returning possible combinations of
	elements from a given set
In-Reply-To: <4C4F91CD.3020902@ieee.org>
References: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>
	<i2nmot$1a1$1@dough.gmane.org>
	<AANLkTikTM9GGOZcKmtQ-yOgxh1cs7tps7mpvAsgc752C@mail.gmail.com>
	<AANLkTimPRRT+8vsiXsNWnwhnAcEkmoYZyoXhj+TPaQ_C@mail.gmail.com>
	<AANLkTimpNHKs=U89NuEQd5OsEitxTh4VYLRfOzG+DddA@mail.gmail.com>
	<4C4F91CD.3020902@ieee.org>
Message-ID: <AANLkTinGKyOxWnpoGzKBFqSyfRPSBBi4B9-smhTd6kxP@mail.gmail.com>

2010/7/28 Dave Angel <davea at ieee.org>

>
>
> ZUXOXUS wrote:
>
>> Oh, I think i got it:
>>
>>
>>
>>> for prod in itertools.product('ABC', 'ABC'):
>>>>>
>>>>>
>>>> print(prod)
>>
>> ('A', 'A')
>> ('A', 'B')
>> ('A', 'C')
>> ('B', 'A')
>> ('B', 'B')
>> ('B', 'C')
>> ('C', 'A')
>> ('C', 'B')
>> ('C', 'C')
>>
>> Thank you very much!!
>>
>> 2010/7/28 ZUXOXUS <zuxoxus at gmail.com>
>>
>>
> You're top-posting, which loses all the context. In this forum, put your
> comments after whatever lines you're quoting.
>
> Your latest version gets the product of two.  But if you want an arbitrary
> number, instead of repeating the iterable ('ABC' in your case), you can use
> a repeat count.  That's presumably what you were trying to do in your
> earlier incantation.  But you forgot the 'repeat' keyword:
>
> for prod in itertools.product('ABC', repeat=4):
>   xxxx
>
> will give you all the four-tuples.
>
> DaveA
>
>
>

> Hey
>

Sorry for the top-posting, I forgot this rule

Thanks for the reminder, Dave Angel, and for the 'repeat' keyword!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/acbacc65/attachment.html>

From evert.rol at gmail.com  Wed Jul 28 12:11:41 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 28 Jul 2010 12:11:41 +0200
Subject: [Tutor] Order Of Operations Question
In-Reply-To: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com>
References: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com>
Message-ID: <8DDD3518-C54F-4C64-A4F1-EE6EA0AAA006@gmail.com>

Sorry, forgot to reply-to-all:


I don't know the book nor the exercise, but see my comments interspersed in the code, and a few general remarks at the bottom

> From a practice exercise in Building Skills In Python page 64 I'm
> working on How Much Does The Atmosphere Weigh? Part 1:
> To check it states that the answer should be app. 10**18kg However,
> and I've checked to make sure that the math I've layed out matches up
> with the texts, I get 5.07360705863e+20
> 
> In the code I have broken the order of operations down to more
> parenthetical, and tried outright, but see nothing obvious about how
> it's strung together. If anyone has had a similar experience with the
> problem given, or see anything blatantly obvious I've done wrong with
> the ordering of operations. I tried to include as much of the
> problem(formulas are just above variables they're used in) as comments
> as possible.
> 
> import math
> def atmosphereWeight():
>   pi = math.pi
>   """Air Pressure (at sea level) P0. This is the long-term average.
>   P0 = 1.01325 ? 10**5"""
>   airPressCLevl = 1.01325*(10**5)
>   gravity = 9.82
>   """We can use g to get the kg of mass from the force of air
> pressure P0. Apply the acceleration of gravity
>   (in m/sec2) to the air pressure (in kg ? m/sec2). This result is
> mass of the atmosphere in kilograms per
>   square meter (kg/m2).
>   Mm2 = P0 ? g"""
>   masAtmoInKgPerSqM = airPressCLevl * gravity

Simply from looking at the units left and right of the equality sign, you'll need to *divide* by g, not multiply: [kg] = [kg m / s^2] / [m / s^2]


>   """Given the mass of air per square meter, we need to know how
> many square meters of surface to apply
>   this mass to. Radius of Earth R in meters, m. This is an average
> radius; our planet isn?t a perfect sphere.
>   R = 6.37 ? 10"""
>   avgRadiusEarth = 6.37 * (10**6)
>   """The area of a Sphere.
>   A = 4?r2"""
>   areaSphere = 4 * pi * (avgRadiusEarth**2)
>   """Mass of atmosphere (in Kg) is the weight per square meter,
> times the number of square meters
>   Ma = P0 ? g ? A"""
>   masEarthAtmoInKgPerSqM = airPressCLevl * gravity * areaSphere

ditto here: divide by gravity, not multiply by it.


>   print(masEarthAtmoInKgPerSqM)
> 
> atmosphereWeight()


Few general remarks:
- the standard way of writing numbers with a power of ten in code is something like 1.01325e5. I guess this is also easier/quicker to execute (not that this code is time-critical, but in general)
- why do you assign masTmoInKgPerSqM, then later not use it when calculating masEarthAtmoInKgPerSqM?
- just use math.pi when calculating areaSphere, instead of "pi = math.pi" and then later using pi. For me, that's just as clear.
- no need to put parentheses around powers; they are evaluated before the multiplication (unless this is what you meant by "to more parenthetical"
- try indenting the comments as well; more readable

Probably not all of the above are necessary, if you wrote this for debugging your problem, but they're just some thoughts that occurred to me.

Enjoy your calculations.

From hugo.yoshi at gmail.com  Wed Jul 28 12:19:33 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Wed, 28 Jul 2010 12:19:33 +0200
Subject: [Tutor] Order Of Operations Question
In-Reply-To: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com>
References: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com>
Message-ID: <AANLkTinbpA_EBetxZJ5Wvr9UtArt0zpq7T-mrmupasY6@mail.gmail.com>

On Wed, Jul 28, 2010 at 11:41 AM, David Hutto <smokefloat at gmail.com> wrote:
> From a practice exercise in Building Skills In Python page 64 I'm
> working on How Much Does The Atmosphere Weigh? Part 1:
> To check it states that the answer should be app. 10**18kg However,
> and I've checked to make sure that the math I've layed out matches up
> with the texts, I get 5.07360705863e+20
>

Either there is an error in the texts, or you have not checked
throughly enough. It goes wrong here:

>    """We can use g to get the kg of mass from the force of air
> pressure P0. Apply the acceleration of gravity
>    (in m/sec2) to the air pressure (in kg ? m/sec2). This result is
> mass of the atmosphere in kilograms per
>    square meter (kg/m2).
>    Mm2 = P0 ? g"""
>    masAtmoInKgPerSqM = airPressCLevl * gravity

The Air pressure is in Pascal, which is kg / (m*s^2), not (kg * m)/s^2
as you state. That is the Newton. Pascal can also be written as
Newton/m^2, which is (M*g)/m^2. So to get mass per square meter, you
should divide by the acceleration g, not multiply.

With that modification I get about 5e18, which seems correct.

Hugo

From rdmoores at gmail.com  Wed Jul 28 13:51:40 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Wed, 28 Jul 2010 04:51:40 -0700
Subject: [Tutor] problem with simple script
Message-ID: <AANLkTinZmDNsjLKHARq6-gyTKuaOPZHh-wyHOzi5TtKB@mail.gmail.com>

I have a practical need for a script that will give me a random int in the
closed interval [n, m]. Please see <http://tutoree7.pastebin.com/xeCjE7bV>.

This works fine when I enter both n and m as, for example, "23, 56", or even
"56, 23". But often the closed interval is [1, m], so I'd like to not have
to enter the 1 in those cases, and just enter, say, "37" to mean the
interval [1, 37]. Highlighted lines 9-11 are my attempt to do this, but it
fails. This seems like it should be so simple to do, but it isn't not for
me. Advice, please.

Thanks,

Dick Moores
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/9028c94e/attachment.html>

From rabidpoobear at gmail.com  Wed Jul 28 14:14:38 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 28 Jul 2010 07:14:38 -0500
Subject: [Tutor] problem with simple script
In-Reply-To: <AANLkTinZmDNsjLKHARq6-gyTKuaOPZHh-wyHOzi5TtKB@mail.gmail.com>
References: <AANLkTinZmDNsjLKHARq6-gyTKuaOPZHh-wyHOzi5TtKB@mail.gmail.com>
Message-ID: <ABB43FCB-0184-4721-A034-A079261D6F6B@gmail.com>

Just do a split of the input from the user on space or comma. If Len() of the split data is 1, do your [1, ...] interval, otherwise do the other interval.

Sent from my iPhone

On Jul 28, 2010, at 6:51 AM, "Richard D. Moores" <rdmoores at gmail.com> wrote:

> I have a practical need for a script that will give me a random int in the closed interval [n, m]. Please see <http://tutoree7.pastebin.com/xeCjE7bV>.
> 
> This works fine when I enter both n and m as, for example, "23, 56", or even "56, 23". But often the closed interval is [1, m], so I'd like to not have to enter the 1 in those cases, and just enter, say, "37" to mean the interval [1, 37]. Highlighted lines 9-11 are my attempt to do this, but it fails. This seems like it should be so simple to do, but it isn't not for me. Advice, please.
> 
> Thanks, 
> 
> Dick Moores
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/b2bc23ce/attachment-0001.html>

From airscorp at otenet.gr  Wed Jul 28 14:16:05 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Wed, 28 Jul 2010 15:16:05 +0300
Subject: [Tutor] problem with simple script
In-Reply-To: <AANLkTinZmDNsjLKHARq6-gyTKuaOPZHh-wyHOzi5TtKB@mail.gmail.com>
References: <AANLkTinZmDNsjLKHARq6-gyTKuaOPZHh-wyHOzi5TtKB@mail.gmail.com>
Message-ID: <4C501F85.6000704@otenet.gr>

On 07/28/2010 02:51 PM, Richard D. Moores wrote:
> I have a practical need for a script that will give me a random int in 
> the closed interval [n, m]. Please see 
> <http://tutoree7.pastebin.com/xeCjE7bV>.
>
> This works fine when I enter both n and m as, for example, "23, 56", 
> or even "56, 23". But often the closed interval is [1, m], so I'd like 
> to not have to enter the 1 in those cases, and just enter, say, "37" 
> to mean the interval [1, 37]. Highlighted lines 9-11 are my attempt to 
> do this, but it fails. This seems like it should be so simple to do, 
> but it isn't not for me. Advice, please.
>
> Thanks,
>
> Dick Moores
>    
Split the input before the if.
Fork based on the length of the resulting list.
:)

Nick

From python at mhockey.us  Wed Jul 28 14:41:49 2010
From: python at mhockey.us (Rod)
Date: Wed, 28 Jul 2010 08:41:49 -0400
Subject: [Tutor] String replace question
Message-ID: <AANLkTinxTw5j8xq2YigG01kA8GgsTYrKO5tgaCynkbva@mail.gmail.com>

Hello,

I need to replace a period (.) in a domain name with a slash period (\.).

I'm attempting to use the string replace method to do this.

Example:

uri = domain.com

uri.replace('.', '\.')

This returns 'domain\\.com'

Is there a way to do this so there is not a double slash before the period?

Thanks for any help,
Rod

From python at mhockey.us  Wed Jul 28 14:59:58 2010
From: python at mhockey.us (Rod)
Date: Wed, 28 Jul 2010 08:59:58 -0400
Subject: [Tutor] String replace question
In-Reply-To: <261472CB-D0B5-4E23-AB03-573F91C5BFF1@gmail.com>
References: <AANLkTinxTw5j8xq2YigG01kA8GgsTYrKO5tgaCynkbva@mail.gmail.com>
	<261472CB-D0B5-4E23-AB03-573F91C5BFF1@gmail.com>
Message-ID: <AANLkTi=AezhsM-17j-HvNPNzQ=zr=eMoD4KN9Gj4ByX=@mail.gmail.com>

> Try
>>>> print uri.replace('.', '\.')
> and you'll find the replacement works fine.
>
> Or write the output to file, and look at the file.
>
> Python shows a representation on its prompt, and thus needs to escape the backslash (by prepending another backslash). Otherwise you might think '\.' was meant, which is simply a '.'.
> But consider:
>>>> uri.replace('.', '\n')
> 'domain\ncom'
>>>> print uri.replace('.', '\n')
> domain
> com
>
> because '\n' is really a different string (character) than a backslash + 'n'.


Thanks, that was very helpful. I was using the interactive interpreter
to test things.

From airscorp at otenet.gr  Wed Jul 28 15:06:01 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Wed, 28 Jul 2010 16:06:01 +0300
Subject: [Tutor] String replace question
In-Reply-To: <AANLkTinxTw5j8xq2YigG01kA8GgsTYrKO5tgaCynkbva@mail.gmail.com>
References: <AANLkTinxTw5j8xq2YigG01kA8GgsTYrKO5tgaCynkbva@mail.gmail.com>
Message-ID: <4C502B39.7020505@otenet.gr>

On 07/28/2010 03:41 PM, Rod wrote:
> Hello,
>
> I need to replace a period (.) in a domain name with a slash period (\.).
>
> I'm attempting to use the string replace method to do this.
>
> Example:
>
> uri = domain.com
>
> uri.replace('.', '\.')
>
> This returns 'domain\\.com'
>
>
>    
Of course it does! Try to print the value. Now the extra backslash is 
gone. Confused yet?

Well, the backslash is an escape character in Python and other languages 
too. It's used for special characters like newlines ( \n ).
But then how can you enter just a backslash by itself? Easy, escape it 
with a backslash. So \ becomes '\\'

The representation under your uri.replace() line reflects that (escaped) 
syntax.
When you're printing it though, you see the string as you meant it to.

So, nothing is wrong with your lines of code , there's only one 
backslash there, it just get's represented as two.

In fact, you should have escaped \. your self writing the line as such:
uri.replace('.', '\\.')
but since \. is not a special character, python is smart enough to not mind

Nick

From davea at ieee.org  Wed Jul 28 15:22:45 2010
From: davea at ieee.org (Dave Angel)
Date: Wed, 28 Jul 2010 09:22:45 -0400
Subject: [Tutor] Calculating and returning possible combinations of
 elements from a given set
In-Reply-To: <AANLkTinGKyOxWnpoGzKBFqSyfRPSBBi4B9-smhTd6kxP@mail.gmail.com>
References: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>	<i2nmot$1a1$1@dough.gmane.org>	<AANLkTikTM9GGOZcKmtQ-yOgxh1cs7tps7mpvAsgc752C@mail.gmail.com>	<AANLkTimPRRT+8vsiXsNWnwhnAcEkmoYZyoXhj+TPaQ_C@mail.gmail.com>	<AANLkTimpNHKs=U89NuEQd5OsEitxTh4VYLRfOzG+DddA@mail.gmail.com>	<4C4F91CD.3020902@ieee.org>
	<AANLkTinGKyOxWnpoGzKBFqSyfRPSBBi4B9-smhTd6kxP@mail.gmail.com>
Message-ID: <4C502F25.6000508@ieee.org>

ZUXOXUS wrote:
> 2010/7/28 Dave Angel <davea at ieee.org>
> <snip>
>> Your latest version gets the product of two.  But if you want an arbitrary
>> number, instead of repeating the iterable ('ABC' in your case), you can use
>> a repeat count.  That's presumably what you were trying to do in your
>> earlier incantation.  But you forgot the 'repeat' keyword:
>>
>> for prod in itertools.product('ABC', repeat=4):
>>   xxxx
>>
>> will give you all the four-tuples.
>>
>> DaveA
>>
>>
>>     
>
> <snip>
> Thanks for the reminder, Dave Angel, and for the 'repeat' keyword!
>
>   
Since you're new to Python, it's probably useful to expound a little 
bit, on how you could have figured it out from the help documentation.

itertools.product(/*iterables/[, /repeat/])

    Cartesian product of input iterables.

    Equivalent to nested for-loops in a generator expression. For
    example, product(A, B) returns the same as ((x,y) for x in A for y
    in B).

    The nested loops cycle like an odometer with the rightmost element
    advancing on every iteration. This pattern creates a lexicographic
    ordering so that if the input?s iterables are sorted, the product
    tuples are emitted in sorted order.

    To compute the product of an iterable with itself, specify the
    number of repetitions with the optional /repeat/ keyword argument.
    For example, product(A, repeat=4) means the same as product(A, A, A, A).

....

Now that example at the end is exactly what you need here. But let's 
look at the first line.

See the *iterables in the formal parameter list. The leading * means you 
can put 1, 2, or as many iterables as you like, and they'll each be 
treated as an independent dimension in the cartesian product. So when 
you put the arguments,
...product("ABC", 2)

the 2 is treated as an iterable, which it isn't. Thus your error. When 
there are an arbitrary number of such arguments, followed by another 
optional parameter, there's no way the compiler could guess in which 
sense you wanted the 2 to be used. So you have to use that parameter's 
name as a keyword in your call. If you have a function declared as
def product(*iterables, repeat):
.....

then you can call it with
count = 4
product(list1, list2, repeat=count)

and by specifying the 'repeat' keyword, the system knows to stop copying 
your arguments into the iterables collection.

Actually, I suspect that if you specify a repeat count, you can only 
supply one iterable, but I'm really talking about the language here.

DaveA





From steve at pearwood.info  Wed Jul 28 16:17:46 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 29 Jul 2010 00:17:46 +1000
Subject: [Tutor] problem with simple script
In-Reply-To: <AANLkTinZmDNsjLKHARq6-gyTKuaOPZHh-wyHOzi5TtKB@mail.gmail.com>
References: <AANLkTinZmDNsjLKHARq6-gyTKuaOPZHh-wyHOzi5TtKB@mail.gmail.com>
Message-ID: <201007290017.46643.steve@pearwood.info>

On Wed, 28 Jul 2010 09:51:40 pm Richard D. Moores wrote:
> I have a practical need for a script that will give me a random int
> in the closed interval [n, m]. Please see
> <http://tutoree7.pastebin.com/xeCjE7bV>.

What is the purpose of this function?

def get_random_int(n, m):
    return randint(n, m)

Why call "get_random_int" instead of randint? It does *exactly* the same 
thing, only slower because of the extra indirection.

If the only reason is because you don't like the name randint, then the 
simple solution is this:

get_random_int = randint

Now get_random_int is another name for the same function, without any 
indirection.


> This works fine when I enter both n and m as, for example, "23, 56",
> or even "56, 23". But often the closed interval is [1, m], so I'd
> like to not have to enter the 1 in those cases, and just enter, say,
> "37" to mean the interval [1, 37]. 

Keep the front end (user interface) separate from the back end. Here's 
the back end:

def get_random_int(n, m=None):
    if m is None:  # only one argument given
        n, m = 1, n
    return randint(n, m)

def str_to_bounds(s):
    L = s.split(',', 1)  # Split a maximum of once.
    return [int(x) for x in L]


And here's the front end:

def get_interval_bounds():
    print("Get a random integer in closed interval [n, m]")
    s = input("Enter n, m: ")
    return str_to_bounds(s)

def main():
    prompt = "Enter 'q' to quit; nothing to get another random int: "
    while True:
        args = get_interval_bounds()
        print(get_random_int(*args))
        ans = input(prompt)
        if ans == 'q':
            print("Bye.") 
            # Waiting 2 seconds is not annoying enough, 
            # waiting 2.2 seconds is too annoying.
            sleep(2.1)  # Just annoying enough!
            return

main()


Hope this helps!



-- 
Steven D'Aprano

From quasipedia at gmail.com  Wed Jul 28 17:07:44 2010
From: quasipedia at gmail.com (Mac Ryan)
Date: Wed, 28 Jul 2010 17:07:44 +0200
Subject: [Tutor] Plugin system - how to manage plugin files?
Message-ID: <1280329664.3061.32.camel@jabbar>

Hi everybody,

	This is more of a python software design question rather than a
question on the Python syntax alone. I hope it is fine to ask here.

	I am working on a small project, that I will release under a GPL
license, whose main design guiding principle is extensibility. Thus I am
trying to make as easy as possible for other devs to create plugins.

	I implemented my plugin system by defining a metaclass, that register -
with a class method - the class name of any plugin that gets loaded (all
plugins inherit from a class defined in the core code). Basically this
means that a developer will have to define his class as:

class PluginMyName(MotherOfAllPlugins)
	do_stuff_here

And the main program will know of his presence because "PluginMyName"
will be included in the list available at "MotherOfAllPlugins.plugins".

Being the mounting method a class method, all plugins get registered
when their class code is loaded into memory (so even before an object of
that class is instantiated).

The system works good enough for me (although I am always open to
suggestions on how to improve the architecture!) but I am now wondering
what would be the best way to manage the plugin files (i.e. where and
how the files containing the plugins should be stored).

So far I am using - for developing purposes - a package that I called
"plugins". I put all my pluginX.py files in the package directory and I
simply have to issue "import plugins" in the main.py file, for all the
plugins to get mounted properly. However this system is only good while
I am developing and testing the code, as:
	1. Plugins might come with their own unittests, and I do not want to
load those in memory.
	2. All plugins are currently loaded into memory, but indeed there are
certain plugins which are alternative versions of the same feature, so
you really just need to know that you can switch between the two, but
you want to load into memory just one.
	3. At some point, I will want to have a double location for installing
plugins: a system-wide location (for example /usr/local/bin/) and a
user-specific one (for example /home/<user>/.myprogram/).

So my questions are really - perhaps - three:

1) What is the most sensible format for the plugin code (a file? a
package? A simple directory of files?)
2) Which is a smart way to use Python introspection to recognise the
presence of plugins without necessarily loading (importing) them.
3) Is there a standard way / best practice (under gnu/linux, at least)
to allow for plugins to be placed in two different locations?

Thank you in advance for your time and guidance,
Mac.


From rdmoores at gmail.com  Wed Jul 28 17:35:56 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Wed, 28 Jul 2010 08:35:56 -0700
Subject: [Tutor] problem with simple script
In-Reply-To: <AANLkTinZmDNsjLKHARq6-gyTKuaOPZHh-wyHOzi5TtKB@mail.gmail.com>
References: <AANLkTinZmDNsjLKHARq6-gyTKuaOPZHh-wyHOzi5TtKB@mail.gmail.com>
Message-ID: <AANLkTineFewgmvgA04LHL2BZU7yHg_Fe5_xt5xVyMsj0@mail.gmail.com>

On Wed, Jul 28, 2010 at 04:51, Richard D. Moores <rdmoores at gmail.com> wrote:
> I have a practical need for a script that will give me a random int in the
> closed interval [n, m]. Please see <http://tutoree7.pastebin.com/xeCjE7bV>.
>
> This works fine when I enter both n and m as, for example, "23, 56", or even
> "56, 23". But often the closed interval is [1, m], so I'd like to not have
> to enter the 1 in those cases, and just enter, say, "37" to mean the
> interval [1, 37]. Highlighted lines 9-11 are my attempt to do this, but it
> fails. This seems like it should be so simple to do, but it isn't not for
> me. Advice, please.

While waiting for replies (they were there, but I had screwed up the
Gmail filter for them and they missed the inbox), I thought I'd just
avoid the need to split, and enter n and m separately. I also added
the ability to get another random int in the same closed interval,
without reentering n and m.

See this effort at <http://tutoree7.pastebin.com/QKvkGiXd>.

Now I'll dig into all the help I received. I see an *args in Steven's
detailed reply. That'll take some reviewing to understand.

Thanks VERY much!

Dick

From abccbg at yahoo.co.uk  Wed Jul 28 18:05:01 2010
From: abccbg at yahoo.co.uk (Alex)
Date: Wed, 28 Jul 2010 16:05:01 +0000 (GMT)
Subject: [Tutor] Problem with input() and unicode string
Message-ID: <746862.12466.qm@web27807.mail.ukl.yahoo.com>

Hello, I have a problem with this code:

# -*- coding: latin-1 -*-
year = u'a?o, ?, ?, ?'
print year
year = input(u'Introduce el a?o:')
print year
raw_input()

The first print statement?works as expected, both in IDLE and when 
double-clicking the file for a console view.
The second one works in IDLE, but?just flashes by when double-clicking the file, 
due to an error report I can't see. 

I believe the problem is that input prompt?doesn't support unicode strings, 
which means I can't use my language for prompts?
Could someone please tell me how to fix it or provide a workaround?
Thanx.

Using Python 2.7 under win32.


      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/81011da1/attachment.html>

From zuxoxus at gmail.com  Wed Jul 28 18:07:25 2010
From: zuxoxus at gmail.com (ZUXOXUS)
Date: Wed, 28 Jul 2010 18:07:25 +0200
Subject: [Tutor] Calculating and returning possible combinations of
	elements from a given set
In-Reply-To: <4C502F25.6000508@ieee.org>
References: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>
	<i2nmot$1a1$1@dough.gmane.org>
	<AANLkTikTM9GGOZcKmtQ-yOgxh1cs7tps7mpvAsgc752C@mail.gmail.com>
	<AANLkTimPRRT+8vsiXsNWnwhnAcEkmoYZyoXhj+TPaQ_C@mail.gmail.com>
	<AANLkTimpNHKs=U89NuEQd5OsEitxTh4VYLRfOzG+DddA@mail.gmail.com>
	<4C4F91CD.3020902@ieee.org>
	<AANLkTinGKyOxWnpoGzKBFqSyfRPSBBi4B9-smhTd6kxP@mail.gmail.com>
	<4C502F25.6000508@ieee.org>
Message-ID: <AANLkTimNxNYu7Z5vdMRQ9Wqhw0uixUmkvzwdju0vRsaL@mail.gmail.com>

>
> 2010/7/28 Dave Angel <davea at ieee.org>
> <snip>
>
> Your latest version gets the product of two.  But if you want an arbitrary
>> number, instead of repeating the iterable ('ABC' in your case), you can
>> use
>> a repeat count.  That's presumably what you were trying to do in your
>> earlier incantation.  But you forgot the 'repeat' keyword:
>>
>> for prod in itertools.product('ABC', repeat=4):
>>  xxxx
>>
>> will give you all the four-tuples.
>>
>> DaveA
>>
>>
>>
>>
>
> <snip>
>
> Thanks for the reminder, Dave Angel, and for the 'repeat' keyword!
>
>
>
Since you're new to Python, it's probably useful to expound a little bit, on
how you could have figured it out from the help documentation.

itertools.product(/*iterables/[, /repeat/])

  Cartesian product of input iterables.

  Equivalent to nested for-loops in a generator expression. For
  example, product(A, B) returns the same as ((x,y) for x in A for y
  in B).

  The nested loops cycle like an odometer with the rightmost element
  advancing on every iteration. This pattern creates a lexicographic
  ordering so that if the input?s iterables are sorted, the product
  tuples are emitted in sorted order.

  To compute the product of an iterable with itself, specify the
  number of repetitions with the optional /repeat/ keyword argument.
  For example, product(A, repeat=4) means the same as product(A, A, A, A).

....

Now that example at the end is exactly what you need here. But let's look at
the first line.

See the *iterables in the formal parameter list. The leading * means you can
put 1, 2, or as many iterables as you like, and they'll each be treated as
an independent dimension in the cartesian product. So when you put the
arguments,
...product("ABC", 2)

the 2 is treated as an iterable, which it isn't. Thus your error. When there
are an arbitrary number of such arguments, followed by another optional
parameter, there's no way the compiler could guess in which sense you wanted
the 2 to be used. So you have to use that parameter's name as a keyword in
your call. If you have a function declared as
def product(*iterables, repeat):
.....

then you can call it with
count = 4
product(list1, list2, repeat=count)

and by specifying the 'repeat' keyword, the system knows to stop copying
your arguments into the iterables collection.

Actually, I suspect that if you specify a repeat count, you can only supply
one iterable, but I'm really talking about the language here.

DaveA

****

Wow, Thank you DaveA, that was very useful.

However, as it usually happens, answers trigger new questions.

My doubt now is whether I can change the way python show the combinations.

I mean, here's what python actually does:

>>> for prod in itertools.product('abc', repeat=3):
print(prod)

('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'a')
('a', 'b', 'b')
('a', 'b', 'c')
[...] etc.


what if I want the combinations listed in a... well, in a list, kind of like
this:

('aaa', 'aab', aac', 'aba', 'abb', 'abc' [...]etc.)

can I do that?

I have checked how the function works (see below), perhaps I have to just
change couple of lines of the code and voil?, the result displayed as I
want... But unfortunately I'm too newbie for this, or this is too hardcore:

def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)


Any ideas will be very much appreciated.

2010/7/28 Dave Angel <davea at ieee.org>

> ZUXOXUS wrote:
>
>> 2010/7/28 Dave Angel <davea at ieee.org>
>> <snip>
>>
>>  Your latest version gets the product of two.  But if you want an
>>> arbitrary
>>> number, instead of repeating the iterable ('ABC' in your case), you can
>>> use
>>> a repeat count.  That's presumably what you were trying to do in your
>>> earlier incantation.  But you forgot the 'repeat' keyword:
>>>
>>> for prod in itertools.product('ABC', repeat=4):
>>>  xxxx
>>>
>>> will give you all the four-tuples.
>>>
>>> DaveA
>>>
>>>
>>>
>>>
>>
>> <snip>
>>
>> Thanks for the reminder, Dave Angel, and for the 'repeat' keyword!
>>
>>
>>
> Since you're new to Python, it's probably useful to expound a little bit,
> on how you could have figured it out from the help documentation.
>
> itertools.product(/*iterables/[, /repeat/])
>
>   Cartesian product of input iterables.
>
>   Equivalent to nested for-loops in a generator expression. For
>   example, product(A, B) returns the same as ((x,y) for x in A for y
>   in B).
>
>   The nested loops cycle like an odometer with the rightmost element
>   advancing on every iteration. This pattern creates a lexicographic
>   ordering so that if the input?s iterables are sorted, the product
>   tuples are emitted in sorted order.
>
>   To compute the product of an iterable with itself, specify the
>   number of repetitions with the optional /repeat/ keyword argument.
>   For example, product(A, repeat=4) means the same as product(A, A, A, A).
>
> ....
>
> Now that example at the end is exactly what you need here. But let's look
> at the first line.
>
> See the *iterables in the formal parameter list. The leading * means you
> can put 1, 2, or as many iterables as you like, and they'll each be treated
> as an independent dimension in the cartesian product. So when you put the
> arguments,
> ...product("ABC", 2)
>
> the 2 is treated as an iterable, which it isn't. Thus your error. When
> there are an arbitrary number of such arguments, followed by another
> optional parameter, there's no way the compiler could guess in which sense
> you wanted the 2 to be used. So you have to use that parameter's name as a
> keyword in your call. If you have a function declared as
> def product(*iterables, repeat):
> .....
>
> then you can call it with
> count = 4
> product(list1, list2, repeat=count)
>
> and by specifying the 'repeat' keyword, the system knows to stop copying
> your arguments into the iterables collection.
>
> Actually, I suspect that if you specify a repeat count, you can only supply
> one iterable, but I'm really talking about the language here.
>
> DaveA
>
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/0c2ed2a9/attachment-0001.html>

From tommy.kaas at kaasogmulvad.dk  Wed Jul 28 18:17:50 2010
From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas)
Date: Wed, 28 Jul 2010 18:17:50 +0200
Subject: [Tutor] Newbie question - syntax - BeautifulSoup
Message-ID: <01ce01cb2e70$6cacf440$4606dcc0$@kaas@kaasogmulvad.dk>

I have just begun a struggle learning Python. I have read most of "Beginning
Python - from Novice to Professional" - and some of it I even understood J

This is my first question to the list. And I'm sure not the last.

 

I'm especially interested in learning web scraping techniques and here:
http://stackoverflow.com/questions/2081586/web-scraping-with-python I found
a small example:

 

import urllib2 

from BeautifulSoup import BeautifulSoup 

 

soup =
BeautifulSoup(urllib2.urlopen('http://www.timeanddate.com/worldclock/astrono
my.html?n=78').read()) 

 

for row in soup('table', {'class' : 'spad'})[0].tbody('tr'): 

  tds = row('td') 

  print tds[0].string, tds[1].string 

  # will print date and sunrise

 

 

 

The example works fine, and I can change it a bit and it still works. But I
simply don't understand how I am supposed to the fourth line - after "for
row in soup". I can clearly see it defines the area I want to scrape, but
how is the syntax build? And almost as important - where should I have found
that information myself? I have tried to read the help-file of
BeautifulSoup, but found nothing there.

 

Thanks in advance.

 

 

Tommy Kaas

Journalist

Kaas & Mulvad

 

Copenhagen, Denmark

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/749d2d01/attachment.html>

From timomlists at gmail.com  Wed Jul 28 18:35:58 2010
From: timomlists at gmail.com (Timo)
Date: Wed, 28 Jul 2010 18:35:58 +0200
Subject: [Tutor] Problem with input() and unicode string
In-Reply-To: <746862.12466.qm@web27807.mail.ukl.yahoo.com>
References: <746862.12466.qm@web27807.mail.ukl.yahoo.com>
Message-ID: <4C505C6E.2080801@gmail.com>

On 28-07-10 18:05, Alex wrote:
> Hello, I have a problem with this code:
> # -*- coding: latin-1 -*-
> year = u'a?o, ?, ?, ?'
> print year
> year = input(u'Introduce el a?o:')
> print year
> raw_input()
> The first print statement works as expected, both in IDLE and when 
> double-clicking the file for a console view.
> The second one works in IDLE, but just flashes by when double-clicking 
> the file, due to an error report I can't see.
I don't have a solution, but call your script from the commandline to 
stay open after exceptions. Or try some things in the Python interactive 
prompt:

 >>> year = input(u'Introduce el a?o:')
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in 
position 14: ordinal not in range(128)

Cheers,
Timo


> I believe the problem is that input prompt doesn't support unicode 
> strings, which means I can't use my language for prompts?
> Could someone please tell me how to fix it or provide a workaround?
> Thanx.
> Using Python 2.7 under win32.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>    


From huyslogic at gmail.com  Wed Jul 28 19:16:23 2010
From: huyslogic at gmail.com (Huy Ton That)
Date: Wed, 28 Jul 2010 13:16:23 -0400
Subject: [Tutor] Problem with input() and unicode string
In-Reply-To: <746862.12466.qm@web27807.mail.ukl.yahoo.com>
References: <746862.12466.qm@web27807.mail.ukl.yahoo.com>
Message-ID: <AANLkTinS57C5G=_vBGcJ8uvF-Ue9SiShd34OSpkF7A=W@mail.gmail.com>

You can do:

input(unicode('Introduce el a?o:', 'latin-1').encode('latin-1'))

Maybe someone could explain it better than I can.

HTH,

Huy

On Wed, Jul 28, 2010 at 12:05 PM, Alex <abccbg at yahoo.co.uk> wrote:

> Hello, I have a problem with this code:
>
> # -*- coding: latin-1 -*-
> year = u'a?o, ?, ?, ?'
> print year
> year = input(u'Introduce el a?o:')
> print year
> raw_input()
>
> The first print statement works as expected, both in IDLE and when
> double-clicking the file for a console view.
> The second one works in IDLE, but just flashes by when double-clicking the
> file, due to an error report I can't see.
> I believe the problem is that input prompt doesn't support unicode strings,
> which means I can't use my language for prompts?
> Could someone please tell me how to fix it or provide a workaround?
> Thanx.
>
> Using Python 2.7 under win32.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/bafcbd7a/attachment.html>

From alan.gauld at btinternet.com  Wed Jul 28 19:18:42 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 28 Jul 2010 18:18:42 +0100
Subject: [Tutor] Running .py files in shell
References: <mailman.5635.1280272049.1671.tutor@python.org>
	<4C4FD09B.6090300@digikev.co.uk>
Message-ID: <i2popg$897$1@dough.gmane.org>

"Kevin Rapley" <kevin at digikev.co.uk> wrote

>> The simplest way is to put a "shebang" line at the top of your 
>> script
>> and then make them executable:
>>
>> $ cat>  myscript.py
> What is the significance of this and how do I use it?

> >>> cat > tryme1.py

Notice the difference in the prompt. A dollar sign is the generic
way of indicating a Unix shell prompt.

cat is a Unix command which catenates the output to a file, again 
using
cat like this is a generic way of sayong create a file containing 
whatever
follows cat. In practice you would use a text editor like vim or pico 
etc.

>>>
means the python prompt. You are typing a Unix command into Python
which doesn't reciognise it, hence the error.

My apologies for not being explicit. I assumed since you were using
the shell to run sudo port install that you were an experienced Unix
shell user and would understand the significance of $.

(Incidentally % is the generic way of indicating a rioot user command,
so

% cat > mydfile

implies login as root (or use sudo) to type the command....)

>> Then use chmod +x to make it executable
>>
>> $ chmod +x myscript.py
> When I try to run this with one of my files I get the following 
> error:
>
> >>> chmod +x tryme1.py

Same problem. chmod is the unix command to Change Mode of a file.

>> $ myscript.py
>>
>> Alternatively you can just call python explicitly:
>>
>> $ python myscript.py
> I get a syntax error doing this too:
>
> >>> python tryme1.py

And again, you type python on its own to start a Python interpreter 
session.
You type, in Unix shell, python file.py to get Python to execute 
file.py

You can find a box explaining some of this in my tutor in the Style 
topic,
near the bottom...

HTH,

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



From alan.gauld at btinternet.com  Wed Jul 28 19:28:24 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 28 Jul 2010 18:28:24 +0100
Subject: [Tutor] Calculating and returning possible combinations
	ofelements from a given set
References: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com><i2nmot$1a1$1@dough.gmane.org><AANLkTikTM9GGOZcKmtQ-yOgxh1cs7tps7mpvAsgc752C@mail.gmail.com><AANLkTimPRRT+8vsiXsNWnwhnAcEkmoYZyoXhj+TPaQ_C@mail.gmail.com><AANLkTimpNHKs=U89NuEQd5OsEitxTh4VYLRfOzG+DddA@mail.gmail.com><4C4F91CD.3020902@ieee.org><AANLkTinGKyOxWnpoGzKBFqSyfRPSBBi4B9-smhTd6kxP@mail.gmail.com><4C502F25.6000508@ieee.org>
	<AANLkTimNxNYu7Z5vdMRQ9Wqhw0uixUmkvzwdju0vRsaL@mail.gmail.com>
Message-ID: <i2ppbm$ad3$1@dough.gmane.org>


"ZUXOXUS" <zuxoxus at gmail.com> wrote


> My doubt now is whether I can change the way python show the 
> combinations.

Python will display the compbinations however you tell it to.
The function generates the combinations the display is up to you.
In this case you are simply printing the results as they come.
But you can put them in a list if you prefer.

>>> prodList = []
>>> for prod in itertools.product('abc', repeat=3):
...           prodList.append(prod)
...
>>> print prodList

You can manipulate prod however you like before putting it inthe list.
Once you have the list you can sort that list to get anyorder you 
want.
And once you have your soted and formatted list you can print it out
using whatever formatting you want.

It is always good to separate the generation of data fropm the
storage of data from the display of data.

> I have checked how the function works (see below), perhaps I have to 
> just
> change couple of lines of the code and voil?, the result displayed 
> as I
> want... But unfortunately I'm too newbie for this, or this is too 
> hardcore:

Its hardly ever a good idea to modify the standard library functions.
You can write a wrapper around them if you like - and indeed thats 
normal.
But changing them is almost always a very bad  idea!

def myProduct(*args, **kwds):
     # do something with input data
     # call itertools.product(args, kwds)
     # do something with the output
     # return a result

HTH,

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



From alan.gauld at btinternet.com  Wed Jul 28 19:45:52 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 28 Jul 2010 18:45:52 +0100
Subject: [Tutor] Order Of Operations Question
References: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com>
Message-ID: <i2pqce$e9s$1@dough.gmane.org>


"David Hutto" <smokefloat at gmail.com> wrote

> To check it states that the answer should be app. 10**18kg However,
> and I've checked to make sure that the math I've layed out matches 
> up
> with the texts, I get 5.07360705863e+20

A couple of comments but my Physics is a bit rusty!!

> import math
> def atmosphereWeight():
>    pi = math.pi
>    """Air Pressure (at sea level) P0. This is the long-term average.
>    P0 = 1.01325 ? 10**5"""

You can express scientific notaton directly:

>    airPressCLevl = 1.01325*(10**5)

airPressCLevl = 1.01325e5

>    gravity = 9.82

It was 9.81 when I was at school.
Doubt if that accounts for the difference though...


>    """We can use g to get the kg of mass from the force of air
> pressure P0. Apply the acceleration of gravity
>    (in m/sec2) to the air pressure (in kg ? m/sec2).

I'd expect pressure to be in Pa or N/m2 or (Kg*m/s2)/m2 = Kg/ms2?

> mass of the atmosphere in kilograms per
>    square meter (kg/m2).
>    Mm2 = P0 ? g"""
>    masAtmoInKgPerSqM = airPressCLevl * gravity

So I'd expect P0/g?

>    """Given the mass of air per square meter, we need to know how
> many square meters of surface to apply
>    this mass to. Radius of Earth R in meters, m. This is an average
> radius; our planet isn?t a perfect sphere.
>    R = 6.37 ? 10"""
>    avgRadiusEarth = 6.37 * (10**6)

I assume the comment's exponent is wrong?! :-)

>    """The area of a Sphere.
>    A = 4?r2"""
>    areaSphere = 4 * pi * (avgRadiusEarth**2)

>    """Mass of atmosphere (in Kg) is the weight per square meter,
> times the number of square meters
>    Ma = P0 ? g ? A"""

>    masEarthAtmoInKgPerSqM = airPressCLevl * gravity * areaSphere

Why don't you use the value you calculated above?

Now if you divide by 10 instead of multiplying by 10 you get a
different of 2 in the exponent?

>    print(masEarthAtmoInKgPerSqM)

HTH,

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



From zuxoxus at gmail.com  Wed Jul 28 19:52:40 2010
From: zuxoxus at gmail.com (ZUXOXUS)
Date: Wed, 28 Jul 2010 19:52:40 +0200
Subject: [Tutor] Calculating and returning possible combinations
	ofelements from a given set
In-Reply-To: <i2ppbm$ad3$1@dough.gmane.org>
References: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>
	<i2nmot$1a1$1@dough.gmane.org>
	<AANLkTikTM9GGOZcKmtQ-yOgxh1cs7tps7mpvAsgc752C@mail.gmail.com>
	<AANLkTimPRRT+8vsiXsNWnwhnAcEkmoYZyoXhj+TPaQ_C@mail.gmail.com>
	<AANLkTimpNHKs=U89NuEQd5OsEitxTh4VYLRfOzG+DddA@mail.gmail.com>
	<4C4F91CD.3020902@ieee.org>
	<AANLkTinGKyOxWnpoGzKBFqSyfRPSBBi4B9-smhTd6kxP@mail.gmail.com>
	<4C502F25.6000508@ieee.org>
	<AANLkTimNxNYu7Z5vdMRQ9Wqhw0uixUmkvzwdju0vRsaL@mail.gmail.com>
	<i2ppbm$ad3$1@dough.gmane.org>
Message-ID: <AANLkTi=25GEynUye+8GzvQBhRHZTZLzNs1bQKTCmXHtb@mail.gmail.com>

2010/7/28 Alan Gauld <alan.gauld at btinternet.com>

>
> "ZUXOXUS" <zuxoxus at gmail.com> wrote
>
>
>
>  My doubt now is whether I can change the way python show the combinations.
>>
>
> Python will display the compbinations however you tell it to.
> The function generates the combinations the display is up to you.
> In this case you are simply printing the results as they come.
> But you can put them in a list if you prefer.
>
>  prodList = []
>>>>
>>>> for prod in itertools.product('abc', repeat=3):
>>>>
>>> ...           prodList.append(prod)
> ...
>
>> print prodList
>>>>
>>>
> You can manipulate prod however you like before putting it inthe list.
> Once you have the list you can sort that list to get anyorder you want.
> And once you have your soted and formatted list you can print it out
> using whatever formatting you want.
>
> It is always good to separate the generation of data fropm the
> storage of data from the display of data.
>
>
>  I have checked how the function works (see below), perhaps I have to just
>> change couple of lines of the code and voil?, the result displayed as I
>> want... But unfortunately I'm too newbie for this, or this is too
>> hardcore:
>>
>
> Its hardly ever a good idea to modify the standard library functions.
> You can write a wrapper around them if you like - and indeed thats normal.
> But changing them is almost always a very bad  idea!
>
> def myProduct(*args, **kwds):
>    # do something with input data
>    # call itertools.product(args, kwds)
>    # do something with the output
>    # return a result
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


Hi Alan and everybody

Well, that is not exactly what I expected, but can help

>>> lista = []
>>> for prod in itertools.product('aei', repeat=2):
lista.append(prod)
print(lista)

[('a', 'a')]
[('a', 'a'), ('a', 'e')]
[('a', 'a'), ('a', 'e'), ('a', 'i')]
[('a', 'a'), ('a', 'e'), ('a', 'i'), ('e', 'a')]
[('a', 'a'), ('a', 'e'), ('a', 'i'), ('e', 'a'), ('e', 'e')]
[('a', 'a'), ('a', 'e'), ('a', 'i'), ('e', 'a'), ('e', 'e'), ('e', 'i')]
[('a', 'a'), ('a', 'e'), ('a', 'i'), ('e', 'a'), ('e', 'e'), ('e', 'i'),
('i', 'a')]
[('a', 'a'), ('a', 'e'), ('a', 'i'), ('e', 'a'), ('e', 'e'), ('e', 'i'),
('i', 'a'), ('i', 'e')]
[('a', 'a'), ('a', 'e'), ('a', 'i'), ('e', 'a'), ('e', 'e'), ('e', 'i'),
('i', 'a'), ('i', 'e'), ('i', 'i')]
>>>


Now I only need to put together in a single string all the elements that are
grouped in parentheses, I think I can do that

Thank you very much!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/81ed531e/attachment.html>

From alan.gauld at btinternet.com  Wed Jul 28 19:53:02 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 28 Jul 2010 18:53:02 +0100
Subject: [Tutor] Problem with input() and unicode string
References: <746862.12466.qm@web27807.mail.ukl.yahoo.com>
Message-ID: <i2pqps$fps$1@dough.gmane.org>


"Alex" <abccbg at yahoo.co.uk> wrote

> The first print statement works as expected, both in IDLE and when
> double-clicking the file for a console view.
> The second one works in IDLE, but just flashes by when 
> double-clicking the file,
> due to an error report I can't see.

So run it from a Console prompt and you will then be able to see the 
error.
That should help you debug it.

HTH,


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



From alan.gauld at btinternet.com  Wed Jul 28 19:59:37 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 28 Jul 2010 18:59:37 +0100
Subject: [Tutor] Newbie question - syntax - BeautifulSoup
References: <9629.7598946423$1280335281@news.gmane.org>
Message-ID: <i2pr67$h3q$1@dough.gmane.org>


"Tommy Kaas" <tommy.kaas at kaasogmulvad.dk> wrote

> for row in soup('table', {'class' : 'spad'})[0].tbody('tr'):
>
> The example works fine, and I can change it a bit and it still 
> works. But I
> simply don't understand how I am supposed to the fourth line - after 
> "for
> row in soup". I can clearly see it defines the area I want to 
> scrape, but
> how is the syntax build?

Do you understand the syntax from a Python point of view?

> that information myself? I have tried to read the help-file of
> BeautifulSoup, but found nothing there.

Which help file?
There is a fairly good tutorial for Beautiful Soup here:

http://www.crummy.com/software/BeautifulSoup/documentation.html

Is that the one you meant?

Did you find the section "Searching By CSS class"?

If so we need more specific questionws about what you don't 
understand.
If not, try reading it and then come back for more... :-)

HTH,

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



From davea at ieee.org  Wed Jul 28 20:00:09 2010
From: davea at ieee.org (Dave Angel)
Date: Wed, 28 Jul 2010 14:00:09 -0400
Subject: [Tutor] Calculating and returning possible combinations of
 elements from a given set
In-Reply-To: <AANLkTimNxNYu7Z5vdMRQ9Wqhw0uixUmkvzwdju0vRsaL@mail.gmail.com>
References: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>	<i2nmot$1a1$1@dough.gmane.org>	<AANLkTikTM9GGOZcKmtQ-yOgxh1cs7tps7mpvAsgc752C@mail.gmail.com>	<AANLkTimPRRT+8vsiXsNWnwhnAcEkmoYZyoXhj+TPaQ_C@mail.gmail.com>	<AANLkTimpNHKs=U89NuEQd5OsEitxTh4VYLRfOzG+DddA@mail.gmail.com>	<4C4F91CD.3020902@ieee.org>	<AANLkTinGKyOxWnpoGzKBFqSyfRPSBBi4B9-smhTd6kxP@mail.gmail.com>	<4C502F25.6000508@ieee.org>
	<AANLkTimNxNYu7Z5vdMRQ9Wqhw0uixUmkvzwdju0vRsaL@mail.gmail.com>
Message-ID: <4C507029.6040702@ieee.org>

ZUXOXUS wrote:
> <snip>
> My doubt now is whether I can change the way python show the combinations.
>
> I mean, here's what python actually does:
>
>   
>>>> for prod in itertools.product('abc', repeat=3):
>>>>         
> print(prod)
>
> ('a', 'a', 'a')
> ('a', 'a', 'b')
> ('a', 'a', 'c')
> ('a', 'b', 'a')
> ('a', 'b', 'b')
> ('a', 'b', 'c')
> [...] etc.
>
>
> what if I want the combinations listed in a... well, in a list, kind of like
> this:
>
> ('aaa', 'aab', aac', 'aba', 'abb', 'abc' [...]etc.)
>
> can I do that?
>
> I have checked how the function works (see below), perhaps I have to just
> change couple of lines of the code and voil?, the result displayed as I
> want... But unfortunately I'm too newbie for this, or this is too hardcore:
>
> def product(*args, **kwds):
>     # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
>     # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
>     pools = map(tuple, args) * kwds.get('repeat', 1)
>     result = [[]]
>     for pool in pools:
>         result = [x+[y] for x in result for y in pool]
>     for prod in result:
>         yield tuple(prod)
>
>
> Any ideas will be very much appreciated.
>
> <snip, double-included history>
Well itertools.product() already returns an iterator that's equivalent 
to a list of tuples.   You can print that list simply by doing something 
like:
print list(itertools.product('abc', repeat=3))

So your question is how you can transform such a list into a list of 
strings instead.

so try each of the following.

for prod in itertools.product('abc', repeat=3):
    print "".join(prod)

print ["".join(prod) for prod in itertools.product('abc', repeat=3)]

DaveA



From sirgnip at gmail.com  Wed Jul 28 20:53:42 2010
From: sirgnip at gmail.com (Scott Nelson)
Date: Wed, 28 Jul 2010 13:53:42 -0500
Subject: [Tutor] Plugin system - how to manage plugin files?
In-Reply-To: <1280329664.3061.32.camel@jabbar>
References: <1280329664.3061.32.camel@jabbar>
Message-ID: <AANLkTik_EgYpZcz2tv--AyoT5_T4GdUPWVQ4mAaDRcwd@mail.gmail.com>

On Wed, Jul 28, 2010 at 10:07 AM, Mac Ryan <quasipedia at gmail.com> wrote:

> Hi everybody,
>
>
Mac,

I don't know if this is exactly what you are after, but I created a
poor-man's plugin system by simply putting .py files into the same directory
as my app and naming them like xxxx_plugin.py  Each of these .py "plugins",
had to define a class named "Plugin" that had some set of expected methods
and properties (ex: initialize(), run(), etc.).  Then, when my app started
up, it simply got a list of all the "*_plugin.py" files in the current
directory, dynamically imported the files using "my_module =
__import__(name)" and then I could do whatever I wanted with that module
using "my_module", such as instantiate an object for each module's "Plugin"
class, etc.

Actually, here's a snippet of code I had lying around that I slapped
together a few years ago to remind myself of how I did this.  I can't
promise this is 100% tested, but it should give you an idea.

http://pastebin.com/UtVp6J9j

Also, you might want to look at this discussion:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/ba8d361516403fdf/

Best of luck!

-Scott
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/d27ebe48/attachment.html>

From tommy.kaas at kaasogmulvad.dk  Wed Jul 28 22:58:59 2010
From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas)
Date: Wed, 28 Jul 2010 22:58:59 +0200
Subject: [Tutor] Newbie question - syntax - BeautifulSoup
In-Reply-To: <i2pr67$h3q$1@dough.gmane.org>
References: <9629.7598946423$1280335281@news.gmane.org>
	<i2pr67$h3q$1@dough.gmane.org>
Message-ID: <021401cb2e97$b3ba46e0$1b2ed4a0$@kaas@kaasogmulvad.dk>

-----Oprindelig meddelelse-----
Fra: tutor-bounces+tommy.kaas=kaasogmulvad.dk at python.org
[mailto:tutor-bounces+tommy.kaas=kaasogmulvad.dk at python.org] P? vegne af
Alan Gauld
Sendt: 28. juli 2010 20:00
Til: tutor at python.org
Emne: Re: [Tutor] Newbie question - syntax - BeautifulSoup


"Tommy Kaas" <tommy.kaas at kaasogmulvad.dk> wrote

> for row in soup('table', {'class' : 'spad'})[0].tbody('tr'):
>
> The example works fine, and I can change it a bit and it still 
> works. But I
> simply don't understand how I am supposed to the fourth line - after 
> "for
> row in soup". I can clearly see it defines the area I want to 
> scrape, but
> how is the syntax build?

Do you understand the syntax from a Python point of view?

No. That's the problem.


> that information myself? I have tried to read the help-file of
> BeautifulSoup, but found nothing there.

Which help file?

Well, maybe not a file, but the text produced by typing: help(BeautifulSoup)



There is a fairly good tutorial for Beautiful Soup here:

http://www.crummy.com/software/BeautifulSoup/documentation.html

Is that the one you meant?

Did you find the section "Searching By CSS class"?

If so we need more specific questionws about what you don't 
understand.
If not, try reading it and then come back for more... :-)

HTH,

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


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


From al.macmillan at me.com  Wed Jul 28 20:59:22 2010
From: al.macmillan at me.com (Alasdair Macmillan)
Date: Wed, 28 Jul 2010 19:59:22 +0100
Subject: [Tutor] A Django Beginner View Question
Message-ID: <B74508C7-51F3-4270-82A4-3DCEFE721413@me.com>

Hi

I am building my first Django site which has a lot of effectively 'static' pages where I just want to make the meta data and text editable.

The model is

models.py

class About(models.Model):
    page_title = models.CharField(max_length=900, help_text='Text at top of browser window')
    meta_keywords = models.CharField(max_length=900, help_text='Keywords (for SEO)')
    meta_description = models.CharField(max_length=160, help_text='Description (for SEO)')
    logo_header = models.CharField(max_length=900, help_text='H1 Header (for SEO)')
    header = models.CharField(max_length=60)
    body = models.TextField()
    last_updated = models.DateTimeField(default=datetime.datetime.now, primary_key=True)
    
    class Meta:
        get_latest_by = "last_updated"
        verbose_name_plural = "About Page"
#        managed = False
    
def __unicode__(self):
    return self.title


I'm trying to understand how to either write a model that only allows a single entry or write a view that will take either a single entry or the most recent entry.

views.py

def about(request):
	return render_to_response('about.html',
								{ 'About' : About.objects.latest() })
urls.py

    (r'^about/$', 'harkproject.cms.views.about'),

Much appreciated
Al Macmillan




From smokefloat at gmail.com  Thu Jul 29 01:00:15 2010
From: smokefloat at gmail.com (David Hutto)
Date: Wed, 28 Jul 2010 19:00:15 -0400
Subject: [Tutor] Order Of Operations Question
In-Reply-To: <8DDD3518-C54F-4C64-A4F1-EE6EA0AAA006@gmail.com>
References: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com>
	<8DDD3518-C54F-4C64-A4F1-EE6EA0AAA006@gmail.com>
Message-ID: <AANLkTikY10DnGoc-8_m_-3fVJNc7Oka=-DO_AmHWS_tn@mail.gmail.com>

On Wed, Jul 28, 2010 at 6:11 AM, Evert Rol <evert.rol at gmail.com> wrote:
> Sorry, forgot to reply-to-all:
>
>
> I don't know the book nor the exercise, but see my comments interspersed in the code, and a few general remarks at the bottom
>
>> From a practice exercise in Building Skills In Python page 64 I'm
>> working on How Much Does The Atmosphere Weigh? Part 1:
>> To check it states that the answer should be app. 10**18kg However,
>> and I've checked to make sure that the math I've layed out matches up
>> with the texts, I get 5.07360705863e+20
>>
>> In the code I have broken the order of operations down to more
>> parenthetical, and tried outright, but see nothing obvious about how
>> it's strung together. If anyone has had a similar experience with the
>> problem given, or see anything blatantly obvious I've done wrong with
>> the ordering of operations. I tried to include as much of the
>> problem(formulas are just above variables they're used in) as comments
>> as possible.
>>
>> import math
>> def atmosphereWeight():
>> ? pi = math.pi
>> ? """Air Pressure (at sea level) P0. This is the long-term average.
>> ? P0 = 1.01325 ? 10**5"""
>> ? airPressCLevl = 1.01325*(10**5)
>> ? gravity = 9.82
>> ? """We can use g to get the kg of mass from the force of air
>> pressure P0. Apply the acceleration of gravity
>> ? (in m/sec2) to the air pressure (in kg ? m/sec2). This result is
>> mass of the atmosphere in kilograms per
>> ? square meter (kg/m2).
>> ? Mm2 = P0 ? g"""
>> ? masAtmoInKgPerSqM = airPressCLevl * gravity
>
> Simply from looking at the units left and right of the equality sign, you'll need to *divide* by g, not multiply: [kg] = [kg m / s^2] / [m / s^2]
>
>
>> ? """Given the mass of air per square meter, we need to know how
>> many square meters of surface to apply
>> ? this mass to. Radius of Earth R in meters, m. This is an average
>> radius; our planet isn?t a perfect sphere.
>> ? R = 6.37 ? 10"""
>> ? avgRadiusEarth = 6.37 * (10**6)
>> ? """The area of a Sphere.
>> ? A = 4?r2"""
>> ? areaSphere = 4 * pi * (avgRadiusEarth**2)
>> ? """Mass of atmosphere (in Kg) is the weight per square meter,
>> times the number of square meters
>> ? Ma = P0 ? g ? A"""
>> ? masEarthAtmoInKgPerSqM = airPressCLevl * gravity * areaSphere
>
> ditto here: divide by gravity, not multiply by it.
>
>
>> ? print(masEarthAtmoInKgPerSqM)
>>
>> atmosphereWeight()
>
>
> Few general remarks:
> - the standard way of writing numbers with a power of ten in code is something like 1.01325e5. I guess this is also easier/quicker to execute (not that this code is time-critical, but in general)

I'll probably ending up reading something about it later in the book,
but as a quick question, why does:

>>> 5e18 == 5**18
False
>>> int(5e18) == int(5**18)
False
>>> 1.01325e5 == 1.01325**5
False

> - why do you assign masTmoInKgPerSqM, then later not use it when calculating masEarthAtmoInKgPerSqM?

I turned all of the formulas given into a variables, however in
masEarthAtmoInKgPerSqM it would have been neater to use
masTmoInKgPerSqM * areaSphere, instead of reusing the two variables
again in .masEarthAtmoInKgPerSqM.


> - just use math.pi when calculating areaSphere, instead of "pi = math.pi" and then later using pi. For me, that's just as clear.
> - no need to put parentheses around powers; they are evaluated before the multiplication (unless this is what you meant by "to more parenthetical"

Yes, it was just to break it into smaller, more readable, pieces.

> - try indenting the comments as well; more readable

It looked better when color coded in the editor, but not here in black
and white.

>
> Probably not all of the above are necessary, if you wrote this for debugging your problem, but they're just some thoughts that occurred to me.
>
> Enjoy your calculations.

Will the 'fun' never end?
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From smokefloat at gmail.com  Thu Jul 29 01:10:16 2010
From: smokefloat at gmail.com (David Hutto)
Date: Wed, 28 Jul 2010 19:10:16 -0400
Subject: [Tutor] Order Of Operations Question
In-Reply-To: <AANLkTinbpA_EBetxZJ5Wvr9UtArt0zpq7T-mrmupasY6@mail.gmail.com>
References: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com>
	<AANLkTinbpA_EBetxZJ5Wvr9UtArt0zpq7T-mrmupasY6@mail.gmail.com>
Message-ID: <AANLkTikMgn9uma+i2zFXQ5261PEcK3mY2AXTQOAa7ALf@mail.gmail.com>

On Wed, Jul 28, 2010 at 6:19 AM, Hugo Arts <hugo.yoshi at gmail.com> wrote:
> On Wed, Jul 28, 2010 at 11:41 AM, David Hutto <smokefloat at gmail.com> wrote:
>> From a practice exercise in Building Skills In Python page 64 I'm
>> working on How Much Does The Atmosphere Weigh? Part 1:
>> To check it states that the answer should be app. 10**18kg However,
>> and I've checked to make sure that the math I've layed out matches up
>> with the texts, I get 5.07360705863e+20
>>
>
> Either there is an error in the texts, or you have not checked
> throughly enough. It goes wrong here:
>
>> ? ?"""We can use g to get the kg of mass from the force of air
>> pressure P0. Apply the acceleration of gravity
>> ? ?(in m/sec2) to the air pressure (in kg ? m/sec2). This result is
>> mass of the atmosphere in kilograms per
>> ? ?square meter (kg/m2).
>> ? ?Mm2 = P0 ? g"""
>> ? ?masAtmoInKgPerSqM = airPressCLevl * gravity
>
> The Air pressure is in Pascal, which is kg / (m*s^2), not (kg * m)/s^2
> as you state. That is the Newton. Pascal can also be written as
> Newton/m^2, which is (M*g)/m^2. So to get mass per square meter, you
> should divide by the acceleration g, not multiply.

In the initial email I did forget this part:
Pressure is measured in Newtons, N, kg m/sec2. Air Pressure is is
measured in Newtons of force per square meter, N/m2.

Which might  have been a more informed question. I was trying not to
add in the whole question, and place the pieces in, but apparently
forgot one.
>
> With that modification I get about 5e18, which seems correct.

I get this with yours and Evert's modification from mult to div, but
if you're right, then the 10e18 the book states as a checker is a
typo/error.

Thanks, for your replies, I'll redo the example again, with a little
more sleep this time. Don't really need to know atmospheric pressure
right now, but might endup at wikipedia/google later.
>
> Hugo
>

From eike.welk at gmx.net  Thu Jul 29 01:25:28 2010
From: eike.welk at gmx.net (Eike Welk)
Date: Thu, 29 Jul 2010 01:25:28 +0200
Subject: [Tutor] Order Of Operations Question
In-Reply-To: <AANLkTikY10DnGoc-8_m_-3fVJNc7Oka=-DO_AmHWS_tn@mail.gmail.com>
References: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com>
	<8DDD3518-C54F-4C64-A4F1-EE6EA0AAA006@gmail.com>
	<AANLkTikY10DnGoc-8_m_-3fVJNc7Oka=-DO_AmHWS_tn@mail.gmail.com>
Message-ID: <201007290125.28522.eike.welk@gmx.net>

Hello David!

On Thursday July 29 2010 01:00:15 David Hutto wrote:

> but as a quick question, why does:
> >>> 5e18 == 5**18
> 
> False

5e18 is a short form of a somewhat complex term:

5e18 == 5 * 10**18 == 5000000000000000000


But 5**18 is just the exponentiation operator:

5**18 == 3814697265625


Eike.

From quasipedia at gmail.com  Thu Jul 29 01:34:07 2010
From: quasipedia at gmail.com (Mac Ryan)
Date: Thu, 29 Jul 2010 01:34:07 +0200
Subject: [Tutor] Plugin system - how to manage plugin files?
In-Reply-To: <AANLkTik_EgYpZcz2tv--AyoT5_T4GdUPWVQ4mAaDRcwd@mail.gmail.com>
References: <1280329664.3061.32.camel@jabbar>
	<AANLkTik_EgYpZcz2tv--AyoT5_T4GdUPWVQ4mAaDRcwd@mail.gmail.com>
Message-ID: <1280360048.3061.57.camel@jabbar>

On Wed, 2010-07-28 at 13:53 -0500, Scott Nelson wrote:
> On Wed, Jul 28, 2010 at 10:07 AM, Mac Ryan <quasipedia at gmail.com>
> wrote:
>         Hi everybody,
>         
> 
> Mac,
> 
> I don't know if this is exactly what you are after, but I created a
> poor-man's plugin system by simply putting .py files into the same
> directory as my app and naming them like xxxx_plugin.py  Each of
> these .py "plugins", had to define a class named "Plugin" that had
> some set of expected methods and properties (ex: initialize(), run(),
> etc.).  Then, when my app started up, it simply got a list of all the
> "*_plugin.py" files in the current directory, dynamically imported the
> files using "my_module = __import__(name)" and then I could do
> whatever I wanted with that module using "my_module", such as
> instantiate an object for each module's "Plugin" class, etc.
> 
> Actually, here's a snippet of code I had lying around that I slapped
> together a few years ago to remind myself of how I did this.  I can't
> promise this is 100% tested, but it should give you an idea.
> 
> http://pastebin.com/UtVp6J9j
> 
> Also, you might want to look at this discussion:
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/ba8d361516403fdf/
> 
> Best of luck!
> 
> -Scott

Thank you Scott for your reply,

I inspected the code you pastebin'd, but I am under the impression the
solution you proposed present about the same shortcomings that mines... 

I recognise that the naming convention of files solve the problem of
having in the same place files which might not be plugins, but the
naming convention is an imposition that I would rather try not to impose
to other devs, the reson being that in my application plugins get
subclassed, so that - if the name of the plugin must be relevant - names
would end up being something like:

   medianvalues_gtk_statistics_scores_plugin.py 

where "medianvalues" would be the name of the plugin, an each other
underscore-separated word would be a parent class.

My hope is that somebody will show me some "automagic obscure voodoo
method" (I am thinking to some "__real_vooodoo__" method or function
somewhere in the module file or in the __init__.py file of the packages)
that will be able to provide information on the plugin without actually
loading it...

Let's see if somebody else will reply to this [admittedly
not-so-popular] thread! ;)

Mac.

PS: About the thread that you linked in your reply: my solution is in
the line of what Fredrik Lundh proposed, using __metaclass___


From hugo.yoshi at gmail.com  Thu Jul 29 01:35:02 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Thu, 29 Jul 2010 01:35:02 +0200
Subject: [Tutor] Order Of Operations Question
In-Reply-To: <AANLkTikMgn9uma+i2zFXQ5261PEcK3mY2AXTQOAa7ALf@mail.gmail.com>
References: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com> 
	<AANLkTinbpA_EBetxZJ5Wvr9UtArt0zpq7T-mrmupasY6@mail.gmail.com> 
	<AANLkTikMgn9uma+i2zFXQ5261PEcK3mY2AXTQOAa7ALf@mail.gmail.com>
Message-ID: <AANLkTin7AMwfbhXrKFu9Gg=aHXLz7TS5vVR8n_R6cvS=@mail.gmail.com>

On Thu, Jul 29, 2010 at 1:10 AM, David Hutto <smokefloat at gmail.com> wrote:
> I get this with yours and Evert's modification from mult to div, but
> if you're right, then the 10e18 the book states as a checker is a
> typo/error.
>

Wait.. in your original e-mail you said the answer as given by the
book was 10**18, not 10e18 (which is of course 10 * 10**18). But
either way, I'd consider 5e18 a correct answer, since it's fairly
close to 1e18 (relatively anyway, it's still 5 times as big). At least
there is not an order of magnitude difference anymore.

Hugo

From smokefloat at gmail.com  Thu Jul 29 01:43:03 2010
From: smokefloat at gmail.com (David Hutto)
Date: Wed, 28 Jul 2010 19:43:03 -0400
Subject: [Tutor] Order Of Operations Question
In-Reply-To: <AANLkTin7AMwfbhXrKFu9Gg=aHXLz7TS5vVR8n_R6cvS=@mail.gmail.com>
References: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com>
	<AANLkTinbpA_EBetxZJ5Wvr9UtArt0zpq7T-mrmupasY6@mail.gmail.com>
	<AANLkTikMgn9uma+i2zFXQ5261PEcK3mY2AXTQOAa7ALf@mail.gmail.com>
	<AANLkTin7AMwfbhXrKFu9Gg=aHXLz7TS5vVR8n_R6cvS=@mail.gmail.com>
Message-ID: <AANLkTimwjmgL2mRXbv5dxpUSHGG1AOHBos1pziTfoaLH@mail.gmail.com>

On Wed, Jul 28, 2010 at 7:35 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote:
> On Thu, Jul 29, 2010 at 1:10 AM, David Hutto <smokefloat at gmail.com> wrote:
>> I get this with yours and Evert's modification from mult to div, but
>> if you're right, then the 10e18 the book states as a checker is a
>> typo/error.
>>
>
> Wait.. in your original e-mail you said the answer as given by the
> book was 10**18,

It is 10**18, in the book, (no e)that was before Eike informed me it
was not the same as 10e18. I stated this after
you used e, and before Eike explained, so I was using 10e18 in the
reply thinking of it as as 10**18.

not 10e18 (which is of course 10 * 10**18). But
> either way, I'd consider 5e18 a correct answer, since it's fairly
> close to 1e18 (relatively anyway, it's still 5 times as big). At least
> there is not an order of magnitude difference anymore.
>
> Hugo
>

From alan.gauld at btinternet.com  Thu Jul 29 01:54:23 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Jul 2010 00:54:23 +0100
Subject: [Tutor] Newbie question - syntax - BeautifulSoup
References: <9629.7598946423$1280335281@news.gmane.org><i2pr67$h3q$1@dough.gmane.org>
	<20181.2883759432$1280350871@news.gmane.org>
Message-ID: <i2qfvd$m0c$1@dough.gmane.org>

"Tommy Kaas" <tommy.kaas at kaasogmulvad.dk> wrote

> > > for row in soup('table', {'class' : 'spad'})[0].tbody('tr'):
> >
> >Do you understand the syntax from a Python point of view?
>
> No. That's the problem.


OK, I'll assume you understand the basic for loop structure
and focus on the function call:

soup('table', {'class' : 'spad'})[0].tbody('tr')

Ignore the bit at the end for now:

soup('table', {'class' : 'spad'})

Thats a call to a function taking a string and a dictionary as 
arguments.
The string says we want to look for table tags. And the dictionary 
says
we want tables that have an attribute class with a value spad.
Is that bit clear?

Then we add an index [0] to get the first table.

Finally we call tbody("tr") to extract the tr tags from the table.
The for loop thus iterates over the rows of the first table with 
class=spad.

There might be slightly more to it than that, its a long time since I
played with BS...

>> Which help file?
>Well, maybe not a file, but the text produced by typing: 
>help(BeautifulSoup)

Ah, in that case you should definitely read the tutorial.

http://www.crummy.com/software/BeautifulSoup/documentation.html

HTH,

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


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

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



From davea at ieee.org  Thu Jul 29 02:03:47 2010
From: davea at ieee.org (Dave Angel)
Date: Wed, 28 Jul 2010 20:03:47 -0400
Subject: [Tutor] Order Of Operations Question
In-Reply-To: <AANLkTikY10DnGoc-8_m_-3fVJNc7Oka=-DO_AmHWS_tn@mail.gmail.com>
References: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com>	<8DDD3518-C54F-4C64-A4F1-EE6EA0AAA006@gmail.com>
	<AANLkTikY10DnGoc-8_m_-3fVJNc7Oka=-DO_AmHWS_tn@mail.gmail.com>
Message-ID: <4C50C563.1050104@ieee.org>



David Hutto wrote:
> <snip>
> I'll probably ending up reading something about it later in the book,
> but as a quick question, why does:
>
>   
>>>> 5e18 =5**18
>>>>         
> False
>   
>>>> int(5e18) =int(5**18)
>>>>         
> False
>   
>>>> 1.01325e5 =1.01325**5
>>>>         
> False
>
>   
The  999e44  notation is intended to be similar to scientific notation, 
where 44 is the exponent, in base 10.

So redoing your equalities:

5e18 == 5*(10**18)
int(5e18) == int(5 * 10**18)
1.01325e5 == 1.01325 * 10**5

The extra parens in the first case, and the extra spaces in the others, are just for readability.  It'd be just as correct to say:
1.01325e5 == 1.01325*10**5

DaveA



From smokefloat at gmail.com  Thu Jul 29 02:13:38 2010
From: smokefloat at gmail.com (David Hutto)
Date: Wed, 28 Jul 2010 20:13:38 -0400
Subject: [Tutor] Order Of Operations Question
In-Reply-To: <4C50C563.1050104@ieee.org>
References: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com>
	<8DDD3518-C54F-4C64-A4F1-EE6EA0AAA006@gmail.com>
	<AANLkTikY10DnGoc-8_m_-3fVJNc7Oka=-DO_AmHWS_tn@mail.gmail.com>
	<4C50C563.1050104@ieee.org>
Message-ID: <AANLkTikpG4OE4vHi_ovsfBZM9ccgDYZRVuNRpjMToFv=@mail.gmail.com>

On Wed, Jul 28, 2010 at 8:03 PM, Dave Angel <davea at ieee.org> wrote:
>
>
> David Hutto wrote:
>>
>> <snip>
>> I'll probably ending up reading something about it later in the book,
>> but as a quick question, why does:
>>
>>
>>>>>
>>>>> 5e18 =5**18
>>>>>
>>
>> False
>>
>>>>>
>>>>> int(5e18) =int(5**18)
>>>>>
>>
>> False
>>
>>>>>
>>>>> 1.01325e5 =1.01325**5
>>>>>
>>
>> False
>>
>>
>
> The ?999e44 ?notation is intended to be similar to scientific notation,
> where 44 is the exponent, in base 10.
>
> So redoing your equalities:
>
> 5e18 == 5*(10**18)
> int(5e18) == int(5 * 10**18)
> 1.01325e5 == 1.01325 * 10**5
>
> The extra parens in the first case, and the extra spaces in the others, are
> just for readability. ?It'd be just as correct to say:
> 1.01325e5 == 1.01325*10**5
>
> DaveA
>
>
>

Already done!

And 5.3*10**18 or 5.2613095377e+18 is the appropriate answer from a
quick google search that resulted in the rounded 5.3e18. So the book
apparently left out the 5.3*, and just gave 10**18.

Thanks for your help, I think this is solved.

From metolone+gmane at gmail.com  Thu Jul 29 05:09:21 2010
From: metolone+gmane at gmail.com (Mark Tolonen)
Date: Wed, 28 Jul 2010 20:09:21 -0700
Subject: [Tutor] Problem with input() and unicode string
References: <746862.12466.qm@web27807.mail.ukl.yahoo.com>
	<i2pqps$fps$1@dough.gmane.org>
Message-ID: <i2qrcp$fpt$1@dough.gmane.org>


"Alan Gauld" <alan.gauld at btinternet.com> wrote in message 
news:i2pqps$fps$1 at dough.gmane.org...
>
> "Alex" <abccbg at yahoo.co.uk> wrote
>
>> The first print statement works as expected, both in IDLE and when
>> double-clicking the file for a console view.
>> The second one works in IDLE, but just flashes by when double-clicking 
>> the file,
>> due to an error report I can't see.
>
> So run it from a Console prompt and you will then be able to see the 
> error.
> That should help you debug it.

Try:

    import sys
    year = raw_input(u'Introduce el a?o:'.encode(sys.stdout.encoding))

Without the explicit encoding I got a UnicodeError due to using the 'ascii' 
codec.

Interesting that 'print' uses the console encoding for Unicode strings, but 
input() and raw_input() don't for their prompts.

You may still get a Unicode error if your console encoding doesn't support 
the characters you are trying to print, but it worked on my US Windows 
'cp437' console.

-Mark



From jmacfiggen at gmail.com  Thu Jul 29 06:01:25 2010
From: jmacfiggen at gmail.com (Jason MacFiggen)
Date: Wed, 28 Jul 2010 21:01:25 -0700
Subject: [Tutor] Python Help - How to end program
Message-ID: <AANLkTinevw8ZJe7fxkTomKs+TbRp=tRMb7sB7pBKT5Me@mail.gmail.com>

Python keeps looping when it gets past the int 0, how do I end the program
when it the int 0 or > 0.

my_hp = 50
    mo_hp = 50
    my_dmg = random.randrange(1, 20)
    mo_dmg = random.randrange(1, 20)
    endProgram = end()
    while True:
        if mo_hp < 0:
            print "The Lich King has been slain!"
        elif my_hp < 0:
            print "You have been slain by the Lich King!"
        if mo_hp <= 0:
            endProgram
        else my_hp <= 0:
            endProgram
        else:
            print "Menu Selections: "
            print "1 - Attack"
            print "2 - Defend"
            print
            choice = input ("Enter your selection. ")
            choice = float(choice)
            print
        if choice == 1:
            mo_hp = mo_hp - my_dmg
            print "The Lich King is at ", mo_hp, "Hit Points"
            print "You did ", my_dmg, "damage!"
            print
            my_hp = my_hp - mo_dmg
            print "I was attacked by the lk for ", mo_dmg," damage!"
            print "My Hit Points are ", my_hp
            print
        elif choice == 2:
            mo_hp = mo_hp - my_dmg / 2
            print "The Lich King is at", mo_hp, "Hit Points"
            print "you did ", my_dmg / 2, "damage!"
            print
            my_hp = my_hp - mo_dmg
            print "I was attacked by the lk for ", mo_dmg," damage!"
            print "My Hit Points are ", my_hp
            print
-Thank you
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/d228c216/attachment.html>

From bsc26 at yahoo.com  Thu Jul 29 06:11:09 2010
From: bsc26 at yahoo.com (Benjamin Castillo)
Date: Wed, 28 Jul 2010 21:11:09 -0700 (PDT)
Subject: [Tutor] Python Help - How to end program
In-Reply-To: <AANLkTinevw8ZJe7fxkTomKs+TbRp=tRMb7sB7pBKT5Me@mail.gmail.com>
Message-ID: <606917.9851.qm@web51405.mail.re2.yahoo.com>

Jason
?
Are you trying to prevent negative numbers?
?
Ben

--- On Wed, 7/28/10, Jason MacFiggen <jmacfiggen at gmail.com> wrote:


From: Jason MacFiggen <jmacfiggen at gmail.com>
Subject: [Tutor] Python Help - How to end program
To: tutor at python.org
Date: Wednesday, July 28, 2010, 9:01 PM



Python keeps looping when it gets past the int 0, how do I end the program when it the int 0 or > 0.
?
my_hp = 50
??? mo_hp = 50
??? my_dmg = random.randrange(1, 20)
??? mo_dmg = random.randrange(1, 20)
??? endProgram = end()
??? while True:
??????? if mo_hp < 0:
??????????? print "The Lich King has been slain!"
??????? elif my_hp < 0:
??????????? print "You have been slain by the Lich King!"
??????? if mo_hp <= 0:
??????????? endProgram
??????? else my_hp <= 0:
??????????? endProgram
??????? else:
??????????? print "Menu Selections: "
??????????? print "1 - Attack"
??????????? print "2 - Defend"
??????????? print
??????????? choice = input ("Enter your selection. ")
??????????? choice = float(choice)
??????????? print
??????? if choice == 1:
??????????? mo_hp = mo_hp - my_dmg
??????????? print "The Lich King is at ", mo_hp, "Hit Points"
??????????? print "You did ", my_dmg, "damage!"
??????????? print
??????????? my_hp = my_hp - mo_dmg
??????????? print "I was attacked by the lk for ", mo_dmg," damage!"
??????????? print "My Hit Points are ", my_hp
??????????? print
??????? elif choice == 2:
??????????? mo_hp = mo_hp - my_dmg / 2
??????????? print "The Lich King is at", mo_hp, "Hit Points"
??????????? print "you did ", my_dmg / 2, "damage!"
??????????? print
??????????? my_hp = my_hp - mo_dmg
??????????? print "I was attacked by the lk for ", mo_dmg," damage!"
??????????? print "My Hit Points are ", my_hp
??????????? print

-Thank you
-----Inline Attachment Follows-----


_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100728/13bdf689/attachment-0001.html>

From metolone+gmane at gmail.com  Thu Jul 29 06:50:24 2010
From: metolone+gmane at gmail.com (Mark Tolonen)
Date: Wed, 28 Jul 2010 21:50:24 -0700
Subject: [Tutor] Python Help - How to end program
References: <AANLkTinevw8ZJe7fxkTomKs+TbRp=tRMb7sB7pBKT5Me@mail.gmail.com>
Message-ID: <i2r1a7$rv9$1@dough.gmane.org>


"Jason MacFiggen" <jmacfiggen at gmail.com> wrote in message 
news:AANLkTinevw8ZJe7fxkTomKs+TbRp=tRMb7sB7pBKT5Me at mail.gmail.com...
> Python keeps looping when it gets past the int 0, how do I end the program
> when it the int 0 or > 0.
>
> my_hp = 50
>    mo_hp = 50
>    my_dmg = random.randrange(1, 20)
>    mo_dmg = random.randrange(1, 20)
>    endProgram = end()
>    while True:
>        if mo_hp < 0:
>            print "The Lich King has been slain!"
>        elif my_hp < 0:
>            print "You have been slain by the Lich King!"
>        if mo_hp <= 0:
>            endProgram
>        else my_hp <= 0:
>            endProgram
>        else:
>            print "Menu Selections: "
>            print "1 - Attack"
>            print "2 - Defend"
>            print
>            choice = input ("Enter your selection. ")
>            choice = float(choice)
>            print
>        if choice == 1:
>            mo_hp = mo_hp - my_dmg
>            print "The Lich King is at ", mo_hp, "Hit Points"
>            print "You did ", my_dmg, "damage!"
>            print
>            my_hp = my_hp - mo_dmg
>            print "I was attacked by the lk for ", mo_dmg," damage!"
>            print "My Hit Points are ", my_hp
>            print
>        elif choice == 2:
>            mo_hp = mo_hp - my_dmg / 2
>            print "The Lich King is at", mo_hp, "Hit Points"
>            print "you did ", my_dmg / 2, "damage!"
>            print
>            my_hp = my_hp - mo_dmg
>            print "I was attacked by the lk for ", mo_dmg," damage!"
>            print "My Hit Points are ", my_hp
>            print

The keyword 'break' will exit a while loop.  Since you have no commands 
after the while loop, that will end your program.

-Mark



From evert.rol at gmail.com  Thu Jul 29 08:57:50 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 29 Jul 2010 08:57:50 +0200
Subject: [Tutor] A Django Beginner View Question
In-Reply-To: <B74508C7-51F3-4270-82A4-3DCEFE721413@me.com>
References: <B74508C7-51F3-4270-82A4-3DCEFE721413@me.com>
Message-ID: <7E551DC4-767A-4393-ADE9-D76A63A1F144@gmail.com>

Consider using the django-users Google group for typical Django questions (unless you figure they're really about Python). Will likely get you better or more answers.
Anyway:

> Hi
> 
> I am building my first Django site which has a lot of effectively 'static' pages where I just want to make the meta data and text editable.

Sounds like you actually want a generic view. Search for the link on the front page of the Django docs. Generic views point your straight from urls.py to the template, bypassing the views.py.
For the second part, you can use the keyword "editable" and set it to False in de model below, for fields you don't want to be edited in the admin (but you'll then have to figure out yourself how to enter the other fields).


> The model is
> 
> models.py
> 
> class About(models.Model):
>    page_title = models.CharField(max_length=900, help_text='Text at top of browser window')
>    meta_keywords = models.CharField(max_length=900, help_text='Keywords (for SEO)')
>    meta_description = models.CharField(max_length=160, help_text='Description (for SEO)')
>    logo_header = models.CharField(max_length=900, help_text='H1 Header (for SEO)')
>    header = models.CharField(max_length=60)
>    body = models.TextField()
>    last_updated = models.DateTimeField(default=datetime.datetime.now, primary_key=True)
> 
>    class Meta:
>        get_latest_by = "last_updated"
>        verbose_name_plural = "About Page"
> #        managed = False
> 
> def __unicode__(self):
>    return self.title
> 
> 
> I'm trying to understand how to either write a model that only allows a single entry or write a view that will take either a single entry or the most recent entry.

Not clear what you want to do: "a model that allows a single entry"? Is that a model which has one, and only one, entry in the database? That doesn't really make much sense. Better do that through your view, as below (again, consider a generic view).


> views.py
> 
> def about(request):
> 	return render_to_response('about.html',
> 								{ 'About' : About.objects.latest() })
> urls.py
> 
>    (r'^about/$', 'harkproject.cms.views.about'),
> 
> Much appreciated
> Al Macmillan


From alan.gauld at btinternet.com  Thu Jul 29 10:07:46 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Jul 2010 09:07:46 +0100
Subject: [Tutor] Python Help - How to end program
References: <AANLkTinevw8ZJe7fxkTomKs+TbRp=tRMb7sB7pBKT5Me@mail.gmail.com>
Message-ID: <i2rcsg$qoo$1@dough.gmane.org>

"Jason MacFiggen" <jmacfiggen at gmail.com> wrote

> Python keeps looping when it gets past the int 0, how do I end the 
> program
> when it the int 0 or > 0.
>
>    while True:
>        if mo_hp < 0:
>            print "The Lich King has been slain!"
>        elif my_hp < 0:

/etc...

When using a while True loop you need ttto have an explicit break
statement somewhere to get out. Personally I like to keep that 
statement
near the top of the loop if possible - just so that I can
find it easily!

So in your case I'd add a test like

if mo_hp >= 0:
    break

right at the top of the loop.

If there were other statements after the loop these would then
get executed but since you don't your program will naturally 
terminate.

Note that if you had an else clause in your while loop(quite unusual)
it does not get executed after a break - the only useful feature I've
found for a loop else condition!

ie

while True:
     break
else:  print 'never executed'
print 'exited'

HTH,

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



From zuxoxus at gmail.com  Thu Jul 29 13:52:37 2010
From: zuxoxus at gmail.com (ZUXOXUS)
Date: Thu, 29 Jul 2010 13:52:37 +0200
Subject: [Tutor] Calculating and returning possible combinations of
	elements from a given set
In-Reply-To: <4C507029.6040702@ieee.org>
References: <AANLkTi=vjoYJK+zrPN6eRgpFT_Ab7RFHZ8XiLs=iWUTm@mail.gmail.com>
	<i2nmot$1a1$1@dough.gmane.org>
	<AANLkTikTM9GGOZcKmtQ-yOgxh1cs7tps7mpvAsgc752C@mail.gmail.com>
	<AANLkTimPRRT+8vsiXsNWnwhnAcEkmoYZyoXhj+TPaQ_C@mail.gmail.com>
	<AANLkTimpNHKs=U89NuEQd5OsEitxTh4VYLRfOzG+DddA@mail.gmail.com>
	<4C4F91CD.3020902@ieee.org>
	<AANLkTinGKyOxWnpoGzKBFqSyfRPSBBi4B9-smhTd6kxP@mail.gmail.com>
	<4C502F25.6000508@ieee.org>
	<AANLkTimNxNYu7Z5vdMRQ9Wqhw0uixUmkvzwdju0vRsaL@mail.gmail.com>
	<4C507029.6040702@ieee.org>
Message-ID: <AANLkTi=2=XAGxzYPUwZWssQHjnx1t6g7h1_T9kokYoD_@mail.gmail.com>

2010/7/28 Dave Angel <davea at ieee.org>

> ZUXOXUS wrote:
>
>> <snip>
>>
>> My doubt now is whether I can change the way python show the combinations.
>>
>> I mean, here's what python actually does:
>>
>>
>>
>>> for prod in itertools.product('abc', repeat=3):
>>>>>
>>>>>
>>>> print(prod)
>>
>> ('a', 'a', 'a')
>> ('a', 'a', 'b')
>> ('a', 'a', 'c')
>> ('a', 'b', 'a')
>> ('a', 'b', 'b')
>> ('a', 'b', 'c')
>> [...] etc.
>>
>>
>> what if I want the combinations listed in a... well, in a list, kind of
>> like
>> this:
>>
>> ('aaa', 'aab', aac', 'aba', 'abb', 'abc' [...]etc.)
>>
>> can I do that?
>>
>> I have checked how the function works (see below), perhaps I have to just
>> change couple of lines of the code and voil?, the result displayed as I
>> want... But unfortunately I'm too newbie for this, or this is too
>> hardcore:
>>
>> def product(*args, **kwds):
>>    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
>>    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
>>    pools = map(tuple, args) * kwds.get('repeat', 1)
>>    result = [[]]
>>    for pool in pools:
>>        result = [x+[y] for x in result for y in pool]
>>    for prod in result:
>>        yield tuple(prod)
>>
>>
>> Any ideas will be very much appreciated.
>>
>> <snip, double-included history>
>>
> Well itertools.product() already returns an iterator that's equivalent to a
> list of tuples.   You can print that list simply by doing something like:
> print list(itertools.product('abc', repeat=3))
>
> So your question is how you can transform such a list into a list of
> strings instead.
>
> so try each of the following.
>
>
> for prod in itertools.product('abc', repeat=3):
>   print "".join(prod)
>
> print ["".join(prod) for prod in itertools.product('abc', repeat=3)]
>
> DaveA
>
>
***

Hi DaveA, the second option returns exactly the result I wanted:

>>> print(["".join(prod) for prod in itertools.product('abc', repeat=3)])
['aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa',
'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 'cac',
'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc']

Thank you very much.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100729/c720e53c/attachment.html>

From norman at khine.net  Thu Jul 29 15:52:02 2010
From: norman at khine.net (Norman Khine)
Date: Thu, 29 Jul 2010 15:52:02 +0200
Subject: [Tutor] finding duplicates within a tuple of tuples
Message-ID: <AANLkTi=FkYcaa9ADrZrwjwBu5OS3m2n3o9s_pNDBC3jq@mail.gmail.com>

hello,

i have this tuple:

http://paste.lisp.org/+2F4X

i have this, which does what i want:

from collections import defaultdict

d = defaultdict(set)
for id, url in result:
	d[url].add(id)
for url in sorted(d):
	if len(d[url]) > 1:
		print('%d -- %s' % (len(d[url]), url))

so here the code checks for duplicate urls and counts the number of occurences.

but i am sort of stuck in that i want to now update the id of the
related table and update the

basically i have two tables:

id, url
24715L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'
24719L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'

id, tid,
1, 24715L
2, 24719L

so i want to first update t(2)'s tid to t(1)'s id for each duplicate
and then delete the row id = 24719L

thanks

-- 
?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo?
?q s,??? ???
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )

From bricker.steve at imonmail.com  Thu Jul 29 18:34:11 2010
From: bricker.steve at imonmail.com (Steve Bricker)
Date: Thu, 29 Jul 2010 11:34:11 -0500
Subject: [Tutor] FTP from mainframe
Message-ID: <42812.1280421251@imonmail.com>

  BODY { font-family:Arial, Helvetica, sans-serif;font-size:12px;
}This is my first attempt to FTP a file from a mainframe.  The code:
 import ftplib
session = ftplib.FTP('company.lan.com','userid','passwd')
myfile = open('PC.filename','w')
session.retrlines("RETR 'mainframe.filename'", myfile)
myfile.close()
session.quit()
 The resulting error is:
 Traceback (most recent call last):
  File "ftp_from_mf.py", line 5, in 
    session.retrlines("RETR 'mainframe.filename'", myfile)
  File "c:python26libftplib.py", line 428, in retrlines
    callback(line)
TypeError: 'file' object is not callable

 Not sure what I'm missing.
 Steve Bricker  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100729/a501a34c/attachment.html>

From __peter__ at web.de  Thu Jul 29 19:05:17 2010
From: __peter__ at web.de (Peter Otten)
Date: Thu, 29 Jul 2010 19:05:17 +0200
Subject: [Tutor] finding duplicates within a tuple of tuples
References: <AANLkTi=FkYcaa9ADrZrwjwBu5OS3m2n3o9s_pNDBC3jq@mail.gmail.com>
Message-ID: <i2scc5$f8n$1@dough.gmane.org>

Norman Khine wrote:

> hello,
> 
> i have this tuple:
> 
> http://paste.lisp.org/+2F4X
> 
> i have this, which does what i want:
> 
> from collections import defaultdict
> 
> d = defaultdict(set)
> for id, url in result:
> d[url].add(id)
> for url in sorted(d):
> if len(d[url]) > 1:
> print('%d -- %s' % (len(d[url]), url))
> 
> so here the code checks for duplicate urls and counts the number of
> occurences.
> 
> but i am sort of stuck in that i want to now update the id of the
> related table and update the
> 
> basically i have two tables:
> 
> id, url
> 24715L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'
> 24719L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'
> 
> id, tid,
> 1, 24715L
> 2, 24719L
> 
> so i want to first update t(2)'s tid to t(1)'s id for each duplicate
> and then delete the row id = 24719L

You can use another dictionary that maps ids associated with the same url to 
a canonical id.

from collections import defaultdict

url_table = [
(24715,"http://aqoon.local/muesli/2-muesli-tropical-500g.html"),
(24719,"http://aqoon.local/muesli/2-muesli-tropical-500g.html"),
(24720,"http://example.com/index.html")
]

id_table = [
(1, 24715),
(2, 24719),
(3, 24720)
]

dupes = defaultdict(set)
for uid, url in url_table:
    dupes[url].add(uid)

lookup = {}
for synonyms in dupes.itervalues():
    if len(synonyms) > 1:
        canonical = min(synonyms)
        for alias in synonyms:
            assert alias not in lookup
            lookup[alias] = canonical

ids = [(id, lookup.get(uid, uid)) for id, uid in id_table]
print ids
urls = [(min(synonyms), url) for url, synonyms in dupes.iteritems()]
print urls

Note that if you use a database for these tables you can avoid creating 
duplicates in the first place.

Peter


From matt.gregory at oregonstate.edu  Thu Jul 29 19:10:35 2010
From: matt.gregory at oregonstate.edu (Gregory, Matthew)
Date: Thu, 29 Jul 2010 10:10:35 -0700
Subject: [Tutor] finding duplicates within a tuple of tuples
Message-ID: <1D673F86DDA00841A1216F04D1CE70D641A8C94237@EXCH2.nws.oregonstate.edu>

Norman Khine wrote:
> basically i have two tables:
> 
> id, url
> 24715L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'
> 24719L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'
> 
> id, tid,
> 1, 24715L
> 2, 24719L
> 
> so i want to first update t(2)'s tid to t(1)'s id for each duplicate
> and then delete the row id = 24719L

Assuming your first table is 'd' and your second table is 't', could you do this?

for url in sorted(d):
    # Get the ID of the first element for updating t's records
    update_id = d[url][0]

    # For all duplicate URLs, remove the dict item from d and
    # update t's records
    while len(d[url]) > 1:
        pop_id = d[url].pop()
        for (k, v) in t.iteritems():
            if v == pop_id:
                t[k] = update_id

There may be a more terse way of updating the values in t that I'm not seeing right now.

matt

From bgailer at gmail.com  Thu Jul 29 19:34:18 2010
From: bgailer at gmail.com (bob gailer)
Date: Thu, 29 Jul 2010 13:34:18 -0400
Subject: [Tutor] FTP from mainframe
In-Reply-To: <42812.1280421251@imonmail.com>
References: <42812.1280421251@imonmail.com>
Message-ID: <4C51BB9A.4070306@gmail.com>

On 7/29/2010 12:34 PM, Steve Bricker wrote:
> This is my first attempt to FTP a file from a mainframe.  The code:
>
> import ftplib
> session = ftplib.FTP('company.lan.com','userid','passwd')
> myfile = open('PC.filename','w')
> session.retrlines("RETR 'mainframe.filename'", myfile)
> myfile.close()
> session.quit()
>
> The resulting error is:
>
> Traceback (most recent call last):
>   File "ftp_from_mf.py", line 5, in <module>
>     session.retrlines("RETR 'mainframe.filename'", myfile)
>   File "c:\python26\lib\ftplib.py", line 428, in retrlines
>     callback(line)
> TypeError: 'file' object is not callable

According to the ftplib module documentation:

retrlines(command[, callback])
Retrieve a file or directory listing in ASCII transfer mode. command 
should be an appropriate RETR command (see retrbinary()) or a command 
such as LIST, NLST or MLSD (usually just the string 'LIST'). The 
callback function is called for each line, with the trailing CRLF 
stripped. The default callback prints the line to sys.stdout.

IOW callback must be a function. You are passing a file object. I will 
guess that you want:

def writer(line):
   myfile.write(line + '\n')

session.retrlines("RETR 'mainframe.filename'", writer)

The documentation is in error in that it does not explicitly state that 
a line is passed to the callback function as an argument. I am assuming 
that is the case.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100729/f4521046/attachment-0001.html>

From alan.gauld at btinternet.com  Thu Jul 29 19:35:00 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Jul 2010 18:35:00 +0100
Subject: [Tutor] FTP from mainframe
References: <42812.1280421251@imonmail.com>
Message-ID: <i2se42$lr2$1@dough.gmane.org>


"Steve Bricker" <bricker.steve at imonmail.com> wrote 

> }This is my first attempt to FTP a file from a mainframe.  

Thats one more than me!

> The resulting error is:
>    session.retrlines("RETR 'mainframe.filename'", myfile)
>  File "c:python26libftplib.py", line 428, in retrlines
>    callback(line)
> TypeError: 'file' object is not callable


The error says that its expecting a callable and you are 
passing a file object. My guess is you need to create a 
function that writes to the file and pass that to ftp.
You could use myfile.write maybe - thats what the 
documentation does for a binary file...

HTH,


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



From bill at celestial.net  Thu Jul 29 20:15:23 2010
From: bill at celestial.net (Bill Campbell)
Date: Thu, 29 Jul 2010 11:15:23 -0700
Subject: [Tutor] FTP from mainframe
In-Reply-To: <4C51BB9A.4070306@gmail.com>
References: <42812.1280421251@imonmail.com> <4C51BB9A.4070306@gmail.com>
Message-ID: <20100729181523.GA1532@ayn.mi.celestial.com>

On Thu, Jul 29, 2010, bob gailer wrote:
>
>   On 7/29/2010 12:34 PM, Steve Bricker wrote:
>
>     This is my first attempt to FTP a file from a mainframe.  The code:
>     import ftplib

The easiest way I've found to get a file via ftp in python is to
user urllib, not ftplib.  Something like this (add error checking).

import urllib, os
fname='something.pdf'
url = 'ftp://%s@%s:%s/%s' % ('john', 'secret', 'example.com', fname)
# f will have a temporary file name, and h the headers
(f, h) = urllib.urlretrieve(url)
os.rename(f, fname)

Of course this works for http by simply changing the url.

Bill
-- 
INTERNET:   bill at celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
Voice:          (206) 236-1676  Mercer Island, WA 98040-0820
Fax:            (206) 232-9186  Skype: jwccsllc (206) 855-5792

If you want government to intervene domestically, you're a liberal.  If you
want government to intervene overseas, you're a conservative.  If you want
government to intervene everywhere, you're a moderate.  If you don't want
government to intervene anywhere, you're an extremist -- Joseph Sobran

From rdmoores at gmail.com  Thu Jul 29 21:22:02 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Thu, 29 Jul 2010 12:22:02 -0700
Subject: [Tutor] problem with simple script
In-Reply-To: <AANLkTineFewgmvgA04LHL2BZU7yHg_Fe5_xt5xVyMsj0@mail.gmail.com>
References: <AANLkTinZmDNsjLKHARq6-gyTKuaOPZHh-wyHOzi5TtKB@mail.gmail.com> 
	<AANLkTineFewgmvgA04LHL2BZU7yHg_Fe5_xt5xVyMsj0@mail.gmail.com>
Message-ID: <AANLkTinjEg+42QwGVzu4wCwuKih5vJ_PM94GPaVetHCs@mail.gmail.com>

On Wed, Jul 28, 2010 at 08:35, Richard D. Moores <rdmoores at gmail.com> wrote:

> Now I'll dig into all the help I received. I see an *args in Steven's
> detailed reply. That'll take some reviewing to understand.

Here's my slight revision of Steven's script (see my note, lines 9-14)
-- revised only because I wanted it to handle the case where the user
(me) entered the interval bounds in the wrong order, e.g., 10, 5
instead of 5, 10.  I've also added a way ('r') for the user to choose
to get another random number in the same interval without having to
reenter the bounds: <http://tutoree7.pastebin.com/XZ2Eek4Z>. Then I
needed a way ('c') to choose to change the bounds after 'r' had been
used. I used a flag (lines 42, 53, 55) to accomplish these additions.
Was there a better way? Should I have written a couple of extra
functions instead of using the flag? Are flags unpythonic?

I've learned a lot from his script, and hope to learn more -- I'm
still grappling with the  *args  of line 46.

What I've learned so far:
1. To separate the front end (for the user) from the back end. See his
note on line 3.
2. The use of maxsplit with str.split(). Line 29.
3. Using the return of a function to call another function. Line 38.
4. In main(), he assigns the prompt to a variable _before_ the while
loop (line 41), so the assignment is done only once, rather than each
time through the loop. Not a biggie in this script, but a good thing
to learn, I think.

So thanks, Steven!

Now, on to *args!

Dick

From smokefloat at gmail.com  Fri Jul 30 03:47:20 2010
From: smokefloat at gmail.com (David Hutto)
Date: Thu, 29 Jul 2010 21:47:20 -0400
Subject: [Tutor] A better way for greatest common divisor
Message-ID: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>

This is basically to get feedback, on a better way to show the
greatest common divisor in fraction, in order to reduce it fully, than
the one I've come up with. I'm sure there are better ways, so if you
have simpler method, or critique of what I've done, let me know.


'''Greatest Common Divisor Function'''
def gcd(num,den):
    while True:
        '''Find if numerator is less than denominator'''
        if num < den:
            '''Range backwards from larger number'''
            for y in range.__reversed__(range(1,den+1)):
                county = y
                '''If den is evenly divisible by county'''
                if den%county == 0:
                    '''And if num is divisible by county'''
                    if num%county == 0:
                        '''We have funneled the largest number\
                        divisible by both, by looping backwards\
                        from the larger number'''
                        print(county,'\n')
                        numdiv = num/county
                        dendiv = den/county
                        print('Reduced value is: %d/%d' % (numdiv,dendiv))
                        break
        '''Below is about the same, except turns the fraction\
        into it's wholenumber/fraction counterpart'''
        if num > den:
            for x in range.__reversed__(range(1,num+1)):
                countx = x
                if num%countx == 0:
                    if den%countx == 0:
                        print(countx)
                        numdiv = num/countx
                        dendiv = den/countx
                        print('Reduced value is: %d/%d' % (numdiv,dendiv))

print(int(numdiv/dendiv),'and',int(numdiv%dendiv),'/',int(dendiv))
                        break
        break

'''Greatest Common Divisor Function Instance'''
num=int(float(input('Input numerator: ')))
den=int(float(input('Input denominator: ')))
gcd(num,den)


David

From prologic at shortcircuit.net.au  Fri Jul 30 04:10:20 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Fri, 30 Jul 2010 12:10:20 +1000
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
Message-ID: <AANLkTin22VoUso0mgo8kuqSzDXBy_zr_2=Dd2e3Q+4gc@mail.gmail.com>

On Fri, Jul 30, 2010 at 11:47 AM, David Hutto <smokefloat at gmail.com> wrote:
> This is basically to get feedback, on a better way to show the
> greatest common divisor in fraction, in order to reduce it fully, than
> the one I've come up with. I'm sure there are better ways, so if you
> have simpler method, or critique of what I've done, let me know.

[snip]

I have a far simpler solution:

>>> from tools import gcd
>>> gcd(20, 5)
5
>>>

def gcd(a, b):
    while b != 0:
        (a, b) = (b, a%b)
    return a

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"

From prologic at shortcircuit.net.au  Fri Jul 30 04:16:46 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Fri, 30 Jul 2010 12:16:46 +1000
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTin22VoUso0mgo8kuqSzDXBy_zr_2=Dd2e3Q+4gc@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com> 
	<AANLkTin22VoUso0mgo8kuqSzDXBy_zr_2=Dd2e3Q+4gc@mail.gmail.com>
Message-ID: <AANLkTinLOg3iQ_eF8qUhkZEgkuEK5Z5My1BSMUyP7NE4@mail.gmail.com>

On Fri, Jul 30, 2010 at 12:10 PM, James Mills
<prologic at shortcircuit.net.au> wrote:
> def gcd(a, b):
> ? ?while b != 0:
> ? ? ? ?(a, b) = (b, a%b)
> ? ?return a

Here's another solution that uses a generator called factors to
generate a list of factors for any given value. The gcd function
then uses sets and intersection and the max function to find
the greatest common factor/divisor

http://codepad.org/VJIRyvI8

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"

From rdmoores at gmail.com  Fri Jul 30 04:22:48 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Thu, 29 Jul 2010 19:22:48 -0700
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTin22VoUso0mgo8kuqSzDXBy_zr_2=Dd2e3Q+4gc@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com> 
	<AANLkTin22VoUso0mgo8kuqSzDXBy_zr_2=Dd2e3Q+4gc@mail.gmail.com>
Message-ID: <AANLkTinAf4SfPjNtLBZV15LKjEifj+Q3yxmvghgp=NX0@mail.gmail.com>

On Thu, Jul 29, 2010 at 19:10, James Mills <prologic at shortcircuit.net.au> wrote:
> On Fri, Jul 30, 2010 at 11:47 AM, David Hutto <smokefloat at gmail.com> wrote:
>> This is basically to get feedback, on a better way to show the
>> greatest common divisor in fraction, in order to reduce it fully, than
>> the one I've come up with. I'm sure there are better ways, so if you
>> have simpler method, or critique of what I've done, let me know.
>
> [snip]
>
> I have a far simpler solution:
>
>>>> from tools import gcd
>>>> gcd(20, 5)
> 5

In Python 3.1 that would be
>>> from fractions import gcd
>>> gcd(20,5)
5

Dick Moores

From prologic at shortcircuit.net.au  Fri Jul 30 04:36:44 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Fri, 30 Jul 2010 12:36:44 +1000
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTinAf4SfPjNtLBZV15LKjEifj+Q3yxmvghgp=NX0@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com> 
	<AANLkTin22VoUso0mgo8kuqSzDXBy_zr_2=Dd2e3Q+4gc@mail.gmail.com> 
	<AANLkTinAf4SfPjNtLBZV15LKjEifj+Q3yxmvghgp=NX0@mail.gmail.com>
Message-ID: <AANLkTim8W3yxZHO73OjQE-BSehJsK9hLA5wh+hWWifyf@mail.gmail.com>

On Fri, Jul 30, 2010 at 12:22 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
> On Thu, Jul 29, 2010 at 19:10, James Mills <prologic at shortcircuit.net.au> wrote:
>> On Fri, Jul 30, 2010 at 11:47 AM, David Hutto <smokefloat at gmail.com> wrote:
>>> This is basically to get feedback, on a better way to show the
>>> greatest common divisor in fraction, in order to reduce it fully, than
>>> the one I've come up with. I'm sure there are better ways, so if you
>>> have simpler method, or critique of what I've done, let me know.
>>
>> [snip]
>>
>> I have a far simpler solution:
>>
>>>>> from tools import gcd
>>>>> gcd(20, 5)
>> 5
>
> In Python 3.1 that would be
>>>> from fractions import gcd
>>>> gcd(20,5)
> 5

Yes. The code I provided above was code I wrote
for various Euler problems I had been working on
a whiel back. It was written for 2.x

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"

From smokefloat at gmail.com  Fri Jul 30 04:48:15 2010
From: smokefloat at gmail.com (David Hutto)
Date: Thu, 29 Jul 2010 22:48:15 -0400
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTim8W3yxZHO73OjQE-BSehJsK9hLA5wh+hWWifyf@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
	<AANLkTin22VoUso0mgo8kuqSzDXBy_zr_2=Dd2e3Q+4gc@mail.gmail.com>
	<AANLkTinAf4SfPjNtLBZV15LKjEifj+Q3yxmvghgp=NX0@mail.gmail.com>
	<AANLkTim8W3yxZHO73OjQE-BSehJsK9hLA5wh+hWWifyf@mail.gmail.com>
Message-ID: <AANLkTinp5_HkEKkySsaEzzHCHSJpg3rRr7+1=XsrQod0@mail.gmail.com>

On Thu, Jul 29, 2010 at 10:36 PM, James Mills
<prologic at shortcircuit.net.au> wrote:
> On Fri, Jul 30, 2010 at 12:22 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
>> On Thu, Jul 29, 2010 at 19:10, James Mills <prologic at shortcircuit.net.au> wrote:
>>> On Fri, Jul 30, 2010 at 11:47 AM, David Hutto <smokefloat at gmail.com> wrote:
>>>> This is basically to get feedback, on a better way to show the
>>>> greatest common divisor in fraction, in order to reduce it fully, than
>>>> the one I've come up with. I'm sure there are better ways, so if you
>>>> have simpler method, or critique of what I've done, let me know.
>>>
>>> [snip]
>>>
>>> I have a far simpler solution:
>>>
>>>>>> from tools import gcd
>>>>>> gcd(20, 5)
>>> 5
>>
>> In Python 3.1 that would be
>>>>> from fractions import gcd
>>>>> gcd(20,5)
>> 5
>
> Yes. The code I provided above was code I wrote
> for various Euler problems I had been working on
> a whiel back. It was written for 2.x
>
> cheers
> James
>
> --
> -- James Mills
> --
> -- "Problems are solved by method"
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Actually, I knew there was a function in one of the modules, this was
for an exercise in Building Skills in python. So it was more from
scratch than use a prebuilt function.

From smokefloat at gmail.com  Fri Jul 30 04:57:19 2010
From: smokefloat at gmail.com (David Hutto)
Date: Thu, 29 Jul 2010 22:57:19 -0400
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTinLOg3iQ_eF8qUhkZEgkuEK5Z5My1BSMUyP7NE4@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
	<AANLkTin22VoUso0mgo8kuqSzDXBy_zr_2=Dd2e3Q+4gc@mail.gmail.com>
	<AANLkTinLOg3iQ_eF8qUhkZEgkuEK5Z5My1BSMUyP7NE4@mail.gmail.com>
Message-ID: <AANLkTimZtQUgV3DVatTWXdxyvDGkT=BC-NFH=mmkFsC6@mail.gmail.com>

On Thu, Jul 29, 2010 at 10:16 PM, James Mills
<prologic at shortcircuit.net.au> wrote:
> On Fri, Jul 30, 2010 at 12:10 PM, James Mills
> <prologic at shortcircuit.net.au> wrote:
>> def gcd(a, b):
>> ? ?while b != 0:
>> ? ? ? ?(a, b) = (b, a%b)
>> ? ?return a

That was pretty short, and sweet.

>
> Here's another solution that uses a generator called factors to
> generate a list of factors for any given value. The gcd function
> then uses sets and intersection and the max function to find
> the greatest common factor/divisor
>
> http://codepad.org/VJIRyvI8
>
> cheers
> James
>
> --
> -- James Mills
> --
> -- "Problems are solved by method"
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From norman at khine.net  Fri Jul 30 05:28:34 2010
From: norman at khine.net (Norman Khine)
Date: Fri, 30 Jul 2010 05:28:34 +0200
Subject: [Tutor] finding duplicates within a tuple of tuples
In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D641A8C94237@EXCH2.nws.oregonstate.edu>
References: <1D673F86DDA00841A1216F04D1CE70D641A8C94237@EXCH2.nws.oregonstate.edu>
Message-ID: <AANLkTi=nucGMMguw+0anpkYr5vaM6NxMuy8GdTcNN30p@mail.gmail.com>

Hello,
Thanks for the replies.

On Thu, Jul 29, 2010 at 7:10 PM, Gregory, Matthew
<matt.gregory at oregonstate.edu> wrote:
> Norman Khine wrote:
>> basically i have two tables:
>>
>> id, url
>> 24715L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'
>> 24719L, 'http://aqoon.local/muesli/2-muesli-tropical-500g.html'
>>
>> id, tid,
>> 1, 24715L
>> 2, 24719L
>>
>> so i want to first update t(2)'s tid to t(1)'s id for each duplicate
>> and then delete the row id = 24719L
>
> Assuming your first table is 'd' and your second table is 't', could you do this?
>
> for url in sorted(d):
> ? ?# Get the ID of the first element for updating t's records
> ? ?update_id = d[url][0]
>
> ? ?# For all duplicate URLs, remove the dict item from d and
> ? ?# update t's records
> ? ?while len(d[url]) > 1:
> ? ? ? ?pop_id = d[url].pop()
> ? ? ? ?for (k, v) in t.iteritems():
> ? ? ? ? ? ?if v == pop_id:
> ? ? ? ? ? ? ? ?t[k] = update_id
>
> There may be a more terse way of updating the values in t that I'm not seeing right now.

Here is the latest version http://pastie.org/1066582 can this be
further improved?

>
> matt
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo?
?q s,??? ???
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )

From cwitts at compuscan.co.za  Fri Jul 30 07:53:28 2010
From: cwitts at compuscan.co.za (Christian Witts)
Date: Fri, 30 Jul 2010 07:53:28 +0200
Subject: [Tutor] FTP from mainframe
In-Reply-To: <42812.1280421251@imonmail.com>
References: <42812.1280421251@imonmail.com>
Message-ID: <4C5268D8.3040707@compuscan.co.za>

On 29/07/2010 18:34, Steve Bricker wrote:
> This is my first attempt to FTP a file from a mainframe.  The code:
>
> import ftplib
> session = ftplib.FTP('company.lan.com','userid','passwd')
> myfile = open('PC.filename','w')
> session.retrlines("RETR 'mainframe.filename'", myfile)
> myfile.close()
> session.quit()
>
> The resulting error is:
>
> Traceback (most recent call last):
>   File "ftp_from_mf.py", line 5, in <module>
>     session.retrlines("RETR 'mainframe.filename'", myfile)
>   File "c:\python26\lib\ftplib.py", line 428, in retrlines
>     callback(line)
> TypeError: 'file' object is not callable
>
> Not sure what I'm missing.
>
> Steve Bricker
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>    

When I'm retrieving items I use retrbinary for eg.

from ftplib import FTP

ftp = FTP(url, username, password)
for filename in ftp.nlst(''):
     ftp.retrbinary('RETR %s' % filename, open(filename, 'wb').write)
     ftp.delete(filename)

ftp.close()

I hope that helps.

-- 
Kind Regards,
Christian Witts
Business Intelligence

C o m p u s c a n | Confidence in Credit

Telephone: +27 21 888 6000
National Cell Centre: 0861 51 41 31
Fax: +27 21 413 2424
E-mail: cwitts at compuscan.co.za

NOTE:  This e-mail (including attachments )is subject to the disclaimer published at: http://www.compuscan.co.za/live/content.php?Item_ID=494.
If you cannot access the disclaimer, request it from email.disclaimer at compuscan.co.za or 0861 514131.

National Credit Regulator Credit Bureau Registration No. NCRCB6



From alan.gauld at btinternet.com  Fri Jul 30 08:35:31 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 30 Jul 2010 07:35:31 +0100
Subject: [Tutor] FTP from mainframe
References: <42812.1280421251@imonmail.com> <4C5268D8.3040707@compuscan.co.za>
Message-ID: <i2trri$llu$1@dough.gmane.org>


"Christian Witts" <cwitts at compuscan.co.za> wrote

> When I'm retrieving items I use retrbinary for eg.
>

The only issue with that is that if this is a real big-iron mainframe
then ftp can translate EBCDIC to ASCII during the transfer whereas
binary will, I think, bring the original file across untranslated.
So you would have the extra decoding step to do manually.
But binary transfer does simplify the transfer process.

But if its not an EBCDIC machine then I'd definitely consider
binary transfer for ftp.

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



From tommy.kaas at kaasogmulvad.dk  Fri Jul 30 08:36:07 2010
From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas)
Date: Fri, 30 Jul 2010 08:36:07 +0200
Subject: [Tutor] Newbie question - syntax - BeautifulSoup
In-Reply-To: <i2qfvd$m0c$1@dough.gmane.org>
References: <9629.7598946423$1280335281@news.gmane.org><i2pr67$h3q$1@dough.gmane.org>	<20181.2883759432$1280350871@news.gmane.org>
	<i2qfvd$m0c$1@dough.gmane.org>
Message-ID: <000501cb2fb1$7e479b50$7ad6d1f0$@kaas@kaasogmulvad.dk>

Thanks for the explanation. It's clearer now.
Tommy

"Tommy Kaas" <tommy.kaas at kaasogmulvad.dk> wrote

> > > for row in soup('table', {'class' : 'spad'})[0].tbody('tr'):
> >
> >Do you understand the syntax from a Python point of view?
>
> No. That's the problem.


OK, I'll assume you understand the basic for loop structure
and focus on the function call:

soup('table', {'class' : 'spad'})[0].tbody('tr')

Ignore the bit at the end for now:

soup('table', {'class' : 'spad'})

Thats a call to a function taking a string and a dictionary as 
arguments.
The string says we want to look for table tags. And the dictionary 
says
we want tables that have an attribute class with a value spad.
Is that bit clear?

Then we add an index [0] to get the first table.

Finally we call tbody("tr") to extract the tr tags from the table.
The for loop thus iterates over the rows of the first table with 
class=spad.

There might be slightly more to it than that, its a long time since I
played with BS...

>> Which help file?
>Well, maybe not a file, but the text produced by typing: 
>help(BeautifulSoup)

Ah, in that case you should definitely read the tutorial.

http://www.crummy.com/software/BeautifulSoup/documentation.html

HTH,

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


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

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


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


From alex.baraibar at gmail.com  Fri Jul 30 10:25:44 2010
From: alex.baraibar at gmail.com (Alex Baraibar)
Date: Fri, 30 Jul 2010 10:25:44 +0200
Subject: [Tutor] Conflict with encoding in console view and file dump
Message-ID: <AANLkTininATGcrQeVRwCW4rAuth6vkLpx96dsOP=DoAE@mail.gmail.com>

Hello, would you please look at the comments in the code and help me with an
answer?
Thanx.

# -*- coding: cp1252 -*-

def festivos():
    fest = [ 'Any Nou:\t\t\t1 de enero',
             'Reis:\t\t\t\t6 de enero',
             'Festa del Treball:\t\t1 de mayo',
             'Sant Joan:\t\t\t24 de junio',
             u'La Assumpci?:\t\t\t15 de agosto',
             'La Diada:\t\t\t11 de septiembre',
             u'La Merc?:\t\t\t24 de septiembre',
             'La Hispanitat:\t\t\t12 de octubre',
             'Tots Sants:\t\t\t1 de novembre',
             u'La Constituci?:\t\t\t6 de desembre',
             u'La Concepci?:\t\t\t8 de desembre',
             'Nadal:\t\t\t\t25 de desembre',
             'Sant Esteve:\t\t\t26 de desembre' ]
    return fest

def separador( num, char ):
    return char * num

# --- Main ---
dias = festivos()
print "Los festivos fijos anuales son:\n"
for element in dias:
    sep = separador( 50, '-' )

    # If I turn off encoding latin-1, accented characters look
    # wrong when I output them to a file from the command line, but
    # if I turn on encoding, accented characters look
    # wrong in the console view.
    print element.encode( 'latin-1' )

    print sep
raw_input()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100730/c2da1c89/attachment-0001.html>

From __peter__ at web.de  Fri Jul 30 10:33:01 2010
From: __peter__ at web.de (Peter Otten)
Date: Fri, 30 Jul 2010 10:33:01 +0200
Subject: [Tutor] finding duplicates within a tuple of tuples
References: <1D673F86DDA00841A1216F04D1CE70D641A8C94237@EXCH2.nws.oregonstate.edu>
	<AANLkTi=nucGMMguw+0anpkYr5vaM6NxMuy8GdTcNN30p@mail.gmail.com>
Message-ID: <i2u2ng$bhv$1@dough.gmane.org>

Norman Khine wrote:

> Here is the latest version http://pastie.org/1066582 can this be
> further improved?

> # get all the duplicates and clean the products table
> main.execute("SELECT product_Id, url FROM %s.product WHERE url != ''" % 
db)
> results = main.fetchall()
> 
> d = defaultdict(set)
> for id, url in results:
> 	d[url].add(id)
> 
> for ids in d.itervalues():
> 	if len(ids) > 1:
> 		# we now hove the first product_id added
> 		canonical = min(ids)
> 		ids = list(ids)
> 		ids.pop(ids.index(canonical))
> 		for id in ids:
> 			update_product_id = 'UPDATE oneproduct.productList_product_assoc SET 
productList_id=%s WHERE productList_id=%s'
> 			main.execute(update_product_id, (id, canonical))
> 			org.commit()
> main.close()

Yes; do it in SQL. Here's my attempt:

# Disclaimer: I stopped at the first point where it seemed to work; don't 
# apply the following on valuable data without extensive prior tests.
 
import sqlite3 
WIDTH = 80
db = sqlite3.connect(":memory:")

url_table = [
(24715,"http://aqoon.local/muesli/2-muesli-tropical-500g.html"),
(24719,"http://aqoon.local/muesli/2-muesli-tropical-500g.html"),
(24720,"http://example.com/index.html")
]
cursor = db.cursor()
cursor.execute("create table alpha (id, url)")
cursor.executemany("insert into alpha values (?, ?)", url_table)

c2 = db.cursor()

id_table = [
(1, 24715),
(2, 24719),
(3, 24720)
]

cursor.execute("create table beta (id, alpha_id)")
cursor.executemany("insert into beta values (?, ?)", id_table)

def show(name):
    print name.center(WIDTH, "-")
    for row in cursor.execute("select * from %s" % name):
        print row
    print

print " BEFORE ".center(WIDTH, "=")
show("alpha")
show("beta")

cursor.execute("""
create view gamma as 
select min(a.id) new_id, b.id old_id from alpha a, alpha b 
where a.url = b.url group by a.url
""")
cursor.execute("""
update beta 
set alpha_id = (select new_id from gamma where alpha_id = old_id) 
where (select new_id from gamma where alpha_id = old_id) is not Null
""")

cursor.execute("""
delete from alpha 
where id not in (select min(b.id) 
from alpha b where alpha.url = b.url)
""")

print " AFTER ".center(WIDTH, "=")
show("alpha")
show("beta")

A database expert could probably simplify that a bit.

Again: duplicate records are best not created rather than removed. If you 
can create a unique index for the url column and alter your insertion code 
appropriately.

Peter


From leo.ruggiero81 at libero.it  Fri Jul 30 13:44:02 2010
From: leo.ruggiero81 at libero.it (leo.ruggiero81 at libero.it)
Date: Fri, 30 Jul 2010 13:44:02 +0200 (CEST)
Subject: [Tutor] Python and Abaqus
Message-ID: <22770163.62001280490242308.JavaMail.defaultUser@defaultHost>

Dear All,

I am trying to have access to the Abaqus kernel by a Python script. My 
intention is to avoid to use the Abaqus GUI (or command line) to run a 
simulation.
The idea is to lunch the Python script by DOS or Python module.

The problem is that my Python script runs from the Abaqus command line or from 
the GUI (menu-->file-->run script) but it doesn't run from outside.

Python doesn't recognize the Abqaus objects (i.e. mdb).

How could I solve this problem?

I need to automate the lunch of Abaqus simulations.

I hope someone could be able to help me.

Thanks a lot.


Regards,


Leo

From __peter__ at web.de  Fri Jul 30 14:01:27 2010
From: __peter__ at web.de (Peter Otten)
Date: Fri, 30 Jul 2010 14:01:27 +0200
Subject: [Tutor] Conflict with encoding in console view and file dump
References: <AANLkTininATGcrQeVRwCW4rAuth6vkLpx96dsOP=DoAE@mail.gmail.com>
Message-ID: <i2ueua$k7e$1@dough.gmane.org>

Alex Baraibar wrote:

> Hello, would you please look at the comments in the code and help me with
> an answer?
> Thanx.
> 
> # -*- coding: cp1252 -*-
> 
> def festivos():
>     fest = [ 'Any Nou:\t\t\t1 de enero',
>              'Reis:\t\t\t\t6 de enero',
>              'Festa del Treball:\t\t1 de mayo',
>              'Sant Joan:\t\t\t24 de junio',
>              u'La Assumpci?:\t\t\t15 de agosto',
>              'La Diada:\t\t\t11 de septiembre',
>              u'La Merc?:\t\t\t24 de septiembre',
>              'La Hispanitat:\t\t\t12 de octubre',
>              'Tots Sants:\t\t\t1 de novembre',
>              u'La Constituci?:\t\t\t6 de desembre',
>              u'La Concepci?:\t\t\t8 de desembre',
>              'Nadal:\t\t\t\t25 de desembre',
>              'Sant Esteve:\t\t\t26 de desembre' ]
>     return fest
> 
> def separador( num, char ):
>     return char * num
> 
> # --- Main ---
> dias = festivos()
> print "Los festivos fijos anuales son:\n"
> for element in dias:
>     sep = separador( 50, '-' )
> 
>     # If I turn off encoding latin-1, accented characters look
>     # wrong when I output them to a file from the command line, but
>     # if I turn on encoding, accented characters look
>     # wrong in the console view.
>     print element.encode( 'latin-1' )
> 
>     print sep
> raw_input()

Hm, I would expect an exception when you redirect the output to a file.
If you add

import sys
print >> sys.stderr, sys.stdout.encoding

what does the above print 
(a) when you print to the console
(b) when you redirect to a file?

Peter


From bala.biophysics at gmail.com  Fri Jul 30 14:36:41 2010
From: bala.biophysics at gmail.com (Bala subramanian)
Date: Fri, 30 Jul 2010 14:36:41 +0200
Subject: [Tutor] problem with subprocess
Message-ID: <AANLkTi=F4hfB6ZaWxQ=grYZPJNN0yg3eeRotrc7e4cXf@mail.gmail.com>

Dear Friends,

I have to do a series of job in a remote machine. I put each job in a text
file called 'job' as and wrote the following code that can read each line in
the text file and execute the job.

I login to the machine and run the script as 'python job.py'. But when i
logout from the machine, the job gets killed. So i submitted the job in
background as 'python job.py &'. Even in this case, when i logout from the
machine, the job gets killed. Why is this so. How can i avoid the same ?

#!/usr/bin/env python
from sys import argv
import subprocess
for line in open('job'):
    subprocess.call(line,shell=True)

Thanks,
Bala
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100730/809b2814/attachment.html>

From knacktus at googlemail.com  Fri Jul 30 15:20:32 2010
From: knacktus at googlemail.com (Knacktus)
Date: Fri, 30 Jul 2010 15:20:32 +0200
Subject: [Tutor] Python and Abaqus
In-Reply-To: <22770163.62001280490242308.JavaMail.defaultUser@defaultHost>
References: <22770163.62001280490242308.JavaMail.defaultUser@defaultHost>
Message-ID: <4C52D1A0.5020708@googlemail.com>

Am 30.07.2010 13:44, schrieb leo.ruggiero81 at libero.it:
> Dear All,
>
> I am trying to have access to the Abaqus kernel by a Python script. My
> intention is to avoid to use the Abaqus GUI (or command line) to run a
> simulation.
> The idea is to lunch the Python script by DOS or Python module.
>
> The problem is that my Python script runs from the Abaqus command line or from
> the GUI (menu-->file-->run script) but it doesn't run from outside.

Without knowing very much about the Abaqus command line my guess is that 
a special environment (env. variables, path, etc.) is set up for the 
Abaqus command line. In that case you need to create that environment in 
your DOS command window where the python script is to run or create that 
environment within your python script (see the os module in the standard 
library).
But prior to that you need to know more about the environment. You could 
query the Abaqus command line (if it's a DOS window by invoking the 
python shell then using os.environ, if it's a Python you can use 
os.environ directly after importing os, of course).
Alternatively you could examine the command file, *.bat file or whatever 
opens the Abaqus command shell. Probably that file has a lot of set up 
stuff in it.

HTH and cheers,

Jan


From hugo.yoshi at gmail.com  Fri Jul 30 15:49:13 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Fri, 30 Jul 2010 15:49:13 +0200
Subject: [Tutor] problem with subprocess
In-Reply-To: <AANLkTi=F4hfB6ZaWxQ=grYZPJNN0yg3eeRotrc7e4cXf@mail.gmail.com>
References: <AANLkTi=F4hfB6ZaWxQ=grYZPJNN0yg3eeRotrc7e4cXf@mail.gmail.com>
Message-ID: <AANLkTinMc+AuXdGgFjc6G0APEB_xs8nGNXu6BW7buP5S@mail.gmail.com>

On Fri, Jul 30, 2010 at 2:36 PM, Bala subramanian
<bala.biophysics at gmail.com> wrote:
> Dear Friends,
>
> I have to do a series of job in a remote machine. I put each job in a text
> file called 'job' as and wrote the following code that can read each line in
> the text file and execute the job.
>

Why not just write a shellscript? that's essentially a list of jobs
anyway. if you make the first line of the file #! /bin/bash you can
basically execute it directly.

> I login to the machine and run the script as 'python job.py'. But when i
> logout from the machine, the job gets killed. So i submitted the job in
> background as 'python job.py &'. Even in this case, when i logout from the
> machine, the job gets killed. Why is this so. How can i avoid the same ?
>

you need to run 'nohup python job.py'. background process still get
SIGHUP when you log out, so they'll still exit.

http://www.computerhope.com/unix/unohup.htm

Hugo

From bala.biophysics at gmail.com  Fri Jul 30 16:10:12 2010
From: bala.biophysics at gmail.com (Bala subramanian)
Date: Fri, 30 Jul 2010 16:10:12 +0200
Subject: [Tutor] problem with subprocess
In-Reply-To: <AANLkTinMc+AuXdGgFjc6G0APEB_xs8nGNXu6BW7buP5S@mail.gmail.com>
References: <AANLkTi=F4hfB6ZaWxQ=grYZPJNN0yg3eeRotrc7e4cXf@mail.gmail.com>
	<AANLkTinMc+AuXdGgFjc6G0APEB_xs8nGNXu6BW7buP5S@mail.gmail.com>
Message-ID: <AANLkTingMDnx1NdmTp+cNR6a03uOk1p+6V1SdJJuxStr@mail.gmail.com>

Thank you so much. I could see the job running with nohup after logout.

Bala

On Fri, Jul 30, 2010 at 3:49 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote:

> On Fri, Jul 30, 2010 at 2:36 PM, Bala subramanian
> <bala.biophysics at gmail.com> wrote:
> > Dear Friends,
> >
> > I have to do a series of job in a remote machine. I put each job in a
> text
> > file called 'job' as and wrote the following code that can read each line
> in
> > the text file and execute the job.
> >
>
> Why not just write a shellscript? that's essentially a list of jobs
> anyway. if you make the first line of the file #! /bin/bash you can
> basically execute it directly.
>
> > I login to the machine and run the script as 'python job.py'. But when i
> > logout from the machine, the job gets killed. So i submitted the job in
> > background as 'python job.py &'. Even in this case, when i logout from
> the
> > machine, the job gets killed. Why is this so. How can i avoid the same ?
> >
>
> you need to run 'nohup python job.py'. background process still get
> SIGHUP when you log out, so they'll still exit.
>
> http://www.computerhope.com/unix/unohup.htm
>
> Hugo
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100730/deb8fd67/attachment.html>

From bgailer at gmail.com  Fri Jul 30 16:29:46 2010
From: bgailer at gmail.com (bob gailer)
Date: Fri, 30 Jul 2010 10:29:46 -0400
Subject: [Tutor] Python and Abaqus
In-Reply-To: <22770163.62001280490242308.JavaMail.defaultUser@defaultHost>
References: <22770163.62001280490242308.JavaMail.defaultUser@defaultHost>
Message-ID: <4C52E1DA.3030801@gmail.com>

On 7/30/2010 7:44 AM, leo.ruggiero81 at libero.it wrote:
> Dear All,
>
> I am trying to have access to the Abaqus kernel by a Python script. My
> intention is to avoid to use the Abaqus GUI (or command line) to run a
> simulation.
> The idea is to lunch the Python script by DOS or Python module.
>    
"lunch" mmm spam?
> The problem is that my Python script runs from the Abaqus command line or from
> the GUI (menu-->file-->run script) but it doesn't run from outside.
>
> Python doesn't recognize the Abqaus objects (i.e. mdb).
>
> How could I solve this problem?
>    

Please learn to ask good questions. In this case specifically:

Tell us what you are doing to "run from outside". Be as specific and 
thorough as possible.

Tell us what results you are getting. Be as specific and thorough as 
possible.

"Doesn't run" and "doesn't recognize" are too vague.

Post your script if not too large else use a pastebin and provide the link.



-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From joel.goldstick at gmail.com  Fri Jul 30 19:33:17 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Fri, 30 Jul 2010 13:33:17 -0400
Subject: [Tutor] A unicode print question
Message-ID: <AANLkTik-vDKF9HyCLPO7WBZweXVUoTgHgYckOjjNZFZD@mail.gmail.com>

I was reading this: http://diveintopython.org/xml_processing/unicode.html

and tried the exercise:

>>> s = u'La Pe\xf1a'         [image: 1]
>>> print s                   [image: 2]
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
UnicodeError: ASCII encoding error: ordinal not in range(128)
>>> print s.encode('latin-1') [image: 3]
La Pe?a

 [image: 1]<http://diveintopython.org/xml_processing/unicode.html#kgp.unicode.2.1>

But oddly enough, when I typed it into my python shell I did NOT get the
UnicodeError, and I wonder why not:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = u'La Pe\xf1a'
>>> print s
La Pe?a
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>


Maybe an earlier version of python produces the error, but not 2.6.5?
-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100730/861f6b84/attachment.html>

From rdmoores at gmail.com  Fri Jul 30 20:57:14 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Fri, 30 Jul 2010 11:57:14 -0700
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
Message-ID: <AANLkTimaLJ03EXXE7+yPUGq51KXn-V5KYR6WECBirJwT@mail.gmail.com>

On Thu, Jul 29, 2010 at 18:47, David Hutto <smokefloat at gmail.com> wrote:
> This is basically to get feedback, on a better way to show the
> greatest common divisor in fraction, in order to reduce it fully, than
> the one I've come up with. I'm sure there are better ways, so if you
> have simpler method, or critique of what I've done, let me know.

I've actually tried to run your script. If it works for you, then I'm
having a problem getting the indents correct. Could you put it up on
<http://python.pastebin.com> or somewhere so it could be copied and
pasted accurately?

Dick Moores

From joel.goldstick at gmail.com  Fri Jul 30 21:01:12 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Fri, 30 Jul 2010 15:01:12 -0400
Subject: [Tutor] A unicode print question
Message-ID: <AANLkTi=dfE=yu2m0n91mp4c6wbHLK-zsWS0dk-5J8FuY@mail.gmail.com>

I was reading this: http://diveintopython.org/xml_processing/unicode.html

and tried the exercise:

>>> s = u'La Pe\xf1a'

>>> print s

Traceback (innermost last):
  File "<interactive input>", line 1, in ?
UnicodeError: ASCII encoding error: ordinal not in range(128)
>>> print s.encode('latin-1')

La Pe?a


But oddly enough, when I typed it into my python shell I did NOT get the
UnicodeError, and I wonder why not:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = u'La Pe\xf1a'
>>> print s
La Pe?a
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>


-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100730/a32c403f/attachment.html>

From malaclypse2 at gmail.com  Fri Jul 30 21:26:33 2010
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Fri, 30 Jul 2010 15:26:33 -0400
Subject: [Tutor] A unicode print question
In-Reply-To: <AANLkTik-vDKF9HyCLPO7WBZweXVUoTgHgYckOjjNZFZD@mail.gmail.com>
References: <AANLkTik-vDKF9HyCLPO7WBZweXVUoTgHgYckOjjNZFZD@mail.gmail.com>
Message-ID: <AANLkTin8wYS3uAxPS66YQ2O7y8Tu+TqNpdKhU4iL4C-7@mail.gmail.com>

On Fri, Jul 30, 2010 at 1:33 PM, Joel Goldstick <joel.goldstick at gmail.com>wrote:

> I was reading this: http://diveintopython.org/xml_processing/unicode.html
>
> and tried the exercise:
>
<snip>

> But oddly enough, when I typed it into my python shell I did NOT get the
> UnicodeError, and I wonder why not:
>

I believe that python is checking the encoding for stdout.  Try this:

print sys.stdout.encoding

When you attempt to print a unicode string, python will attempt to encode it
based on what it autodetected about your terminal.

-- 
Jerry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100730/2b7446d5/attachment.html>

From __peter__ at web.de  Fri Jul 30 21:48:12 2010
From: __peter__ at web.de (Peter Otten)
Date: Fri, 30 Jul 2010 21:48:12 +0200
Subject: [Tutor] A unicode print question
References: <AANLkTik-vDKF9HyCLPO7WBZweXVUoTgHgYckOjjNZFZD@mail.gmail.com>
Message-ID: <i2va9c$lbd$1@dough.gmane.org>

Joel Goldstick wrote:

> I was reading this: http://diveintopython.org/xml_processing/unicode.html
> 
> and tried the exercise:
> 
>>>> s = u'La Pe\xf1a'         [image: 1]
>>>> print s                   [image: 2]
> Traceback (innermost last):
>   File "<interactive input>", line 1, in ?
> UnicodeError: ASCII encoding error: ordinal not in range(128)
>>>> print s.encode('latin-1') [image: 3]
> La Pe?a
> 
>  [image:
>  
[1]<http://diveintopython.org/xml_processing/unicode.html#kgp.unicode.2.1>
> 
> But oddly enough, when I typed it into my python shell I did NOT get the
> UnicodeError, and I wonder why not:
> 
> Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
> [GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> s = u'La Pe\xf1a'
>>>> print s
> La Pe?a
>>>> import sys
>>>> sys.getdefaultencoding()
> 'ascii'
>>
> 
> 
> Maybe an earlier version of python produces the error, but not 2.6.5?

This works a bit differently, probably since Python 2.3. See

http://docs.python.org/library/stdtypes.html#file.encoding

The "old" behaviour may still bite you when you redirect stdout.

$ python -c"print u'Pe\xf1a'"
Pe?a
$ python -c"print u'Pe\xf1a'" > /dev/null
Traceback (most recent call last):
  File "<string>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 
2: ordinal not in range(128)

Peter


From smokefloat at gmail.com  Sat Jul 31 02:43:57 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 30 Jul 2010 20:43:57 -0400
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTimaLJ03EXXE7+yPUGq51KXn-V5KYR6WECBirJwT@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
	<AANLkTimaLJ03EXXE7+yPUGq51KXn-V5KYR6WECBirJwT@mail.gmail.com>
Message-ID: <AANLkTimxKVxL0=rpiCACPANB1fd_0E_uL5Ck_JtxRMQ1@mail.gmail.com>

On Fri, Jul 30, 2010 at 2:57 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
> On Thu, Jul 29, 2010 at 18:47, David Hutto <smokefloat at gmail.com> wrote:
>> This is basically to get feedback, on a better way to show the
>> greatest common divisor in fraction, in order to reduce it fully, than
>> the one I've come up with. I'm sure there are better ways, so if you
>> have simpler method, or critique of what I've done, let me know.
>
> I've actually tried to run your script. If it works for you, then I'm
> having a problem getting the indents correct. Could you put it up on
> <http://python.pastebin.com> or somewhere so it could be copied and
> pasted accurately?
>
> Dick Moores
>

This is the url:
http://python.pastebin.com/fP3jjqGj

From rdmoores at gmail.com  Sat Jul 31 04:25:26 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Fri, 30 Jul 2010 19:25:26 -0700
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTimxKVxL0=rpiCACPANB1fd_0E_uL5Ck_JtxRMQ1@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com> 
	<AANLkTimaLJ03EXXE7+yPUGq51KXn-V5KYR6WECBirJwT@mail.gmail.com> 
	<AANLkTimxKVxL0=rpiCACPANB1fd_0E_uL5Ck_JtxRMQ1@mail.gmail.com>
Message-ID: <AANLkTikbC8jbiYqzisSNzJtH+wtwrg_xk4h4zhMU6+nt@mail.gmail.com>

On Fri, Jul 30, 2010 at 17:43, David Hutto <smokefloat at gmail.com> wrote:
> This is the url:
> http://python.pastebin.com/fP3jjqGj

This is a slight revision, with my suggested changes highlighted:
<http://python.pastebin.com/uFznsUYZ>

Dick Moores

From smokefloat at gmail.com  Sat Jul 31 04:42:02 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 30 Jul 2010 22:42:02 -0400
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTikbC8jbiYqzisSNzJtH+wtwrg_xk4h4zhMU6+nt@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
	<AANLkTimaLJ03EXXE7+yPUGq51KXn-V5KYR6WECBirJwT@mail.gmail.com>
	<AANLkTimxKVxL0=rpiCACPANB1fd_0E_uL5Ck_JtxRMQ1@mail.gmail.com>
	<AANLkTikbC8jbiYqzisSNzJtH+wtwrg_xk4h4zhMU6+nt@mail.gmail.com>
Message-ID: <AANLkTin8=SpTUL5Q5AZuEWZx9Z602YXWqYva_nQG6qV6@mail.gmail.com>

On Fri, Jul 30, 2010 at 10:25 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
> On Fri, Jul 30, 2010 at 17:43, David Hutto <smokefloat at gmail.com> wrote:
>> This is the url:
>> http://python.pastebin.com/fP3jjqGj
>
> This is a slight revision, with my suggested changes highlighted:
> <http://python.pastebin.com/uFznsUYZ>
>
> Dick Moores
>
Before I  see it, here is my revised that shaved a whole 4 lines off
the original. I took out the comments before comparing, so the
pastebin count on the first is off by those comment lines.

http://python.pastebin.com/auw36h87

From smokefloat at gmail.com  Sat Jul 31 04:42:40 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 30 Jul 2010 22:42:40 -0400
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTin8=SpTUL5Q5AZuEWZx9Z602YXWqYva_nQG6qV6@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
	<AANLkTimaLJ03EXXE7+yPUGq51KXn-V5KYR6WECBirJwT@mail.gmail.com>
	<AANLkTimxKVxL0=rpiCACPANB1fd_0E_uL5Ck_JtxRMQ1@mail.gmail.com>
	<AANLkTikbC8jbiYqzisSNzJtH+wtwrg_xk4h4zhMU6+nt@mail.gmail.com>
	<AANLkTin8=SpTUL5Q5AZuEWZx9Z602YXWqYva_nQG6qV6@mail.gmail.com>
Message-ID: <AANLkTimVkW4cBKjEcfkxwmPzgxRp5ELry5aGrhj5qyFb@mail.gmail.com>

On Fri, Jul 30, 2010 at 10:42 PM, David Hutto <smokefloat at gmail.com> wrote:
> On Fri, Jul 30, 2010 at 10:25 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
>> On Fri, Jul 30, 2010 at 17:43, David Hutto <smokefloat at gmail.com> wrote:
>>> This is the url:
>>> http://python.pastebin.com/fP3jjqGj
>>
>> This is a slight revision, with my suggested changes highlighted:
>> <http://python.pastebin.com/uFznsUYZ>
>>
>> Dick Moores
>>
> Before I ?see it, here is my revised that shaved a whole 4 lines off
> the original. I took out the comments before comparing, so the
> pastebin count on the first is off by those comment lines.
forgot the link:
http://python.pastebin.com/auw36h87

From smokefloat at gmail.com  Sat Jul 31 04:43:04 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 30 Jul 2010 22:43:04 -0400
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTikbC8jbiYqzisSNzJtH+wtwrg_xk4h4zhMU6+nt@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
	<AANLkTimaLJ03EXXE7+yPUGq51KXn-V5KYR6WECBirJwT@mail.gmail.com>
	<AANLkTimxKVxL0=rpiCACPANB1fd_0E_uL5Ck_JtxRMQ1@mail.gmail.com>
	<AANLkTikbC8jbiYqzisSNzJtH+wtwrg_xk4h4zhMU6+nt@mail.gmail.com>
Message-ID: <AANLkTinsLf6AcPECY4UMyfXiYdX0+tzerFiTveXNXm+A@mail.gmail.com>

On Fri, Jul 30, 2010 at 10:25 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
> On Fri, Jul 30, 2010 at 17:43, David Hutto <smokefloat at gmail.com> wrote:
>> This is the url:
>> http://python.pastebin.com/fP3jjqGj
>
> This is a slight revision, with my suggested changes highlighted:
> <http://python.pastebin.com/uFznsUYZ>
>
> Dick Moores
>

http://python.pastebin.com/auw36h87

From smokefloat at gmail.com  Sat Jul 31 04:44:53 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 30 Jul 2010 22:44:53 -0400
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTinsLf6AcPECY4UMyfXiYdX0+tzerFiTveXNXm+A@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
	<AANLkTimaLJ03EXXE7+yPUGq51KXn-V5KYR6WECBirJwT@mail.gmail.com>
	<AANLkTimxKVxL0=rpiCACPANB1fd_0E_uL5Ck_JtxRMQ1@mail.gmail.com>
	<AANLkTikbC8jbiYqzisSNzJtH+wtwrg_xk4h4zhMU6+nt@mail.gmail.com>
	<AANLkTinsLf6AcPECY4UMyfXiYdX0+tzerFiTveXNXm+A@mail.gmail.com>
Message-ID: <AANLkTinS5izbK9Lx_diMWT2d8DjW+4Bn8JpwHBShNRqU@mail.gmail.com>

On Fri, Jul 30, 2010 at 10:43 PM, David Hutto <smokefloat at gmail.com> wrote:
> On Fri, Jul 30, 2010 at 10:25 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
>> On Fri, Jul 30, 2010 at 17:43, David Hutto <smokefloat at gmail.com> wrote:
>>> This is the url:
>>> http://python.pastebin.com/fP3jjqGj
>>
>> This is a slight revision, with my suggested changes highlighted:
>> <http://python.pastebin.com/uFznsUYZ>
>>
>> Dick Moores
>>
>
> http://python.pastebin.com/auw36h87
>

Maybe this time gmail will post the link, it keeps showing blank when I send::
http://pastebin.com/auw36h87

From jmacfiggen at gmail.com  Sat Jul 31 04:49:36 2010
From: jmacfiggen at gmail.com (Jason MacFiggen)
Date: Fri, 30 Jul 2010 19:49:36 -0700
Subject: [Tutor] Python - RPG Combat System
Message-ID: <AANLkTi=N41TC-6qSqhD1CGwBV+q61L92Rg_zdNp=1m-_@mail.gmail.com>

I am have trouble figuring out how to make my program stop at 0 hit
points.... if I run it, it always goes into the negative hitpoints...

So my question is how do I make this program end at exactly 0 hit points
every time instead of going over?

and also, what can I do instead of writing print so many times?

import random
    my_hp = 50
    mo_hp = 50
    my_dmg = random.randrange(1, 20)
    mo_dmg = random.randrange(1, 20)
    while True:
        if mo_hp < 0:
            print "The Lich King has been slain!"
        elif my_hp < 0:
            print "You have been slain by the Lich King!"
        if mo_hp <= 0:
            break
        elif my_hp <= 0:
            break
        else:
            print "Menu Selections: "
            print "1 - Attack"
            print "2 - Defend"
            print
            choice = input ("Enter your selection. ")
            choice = float(choice)
            print
        if choice == 1:
            mo_hp = mo_hp - my_dmg
            print "The Lich King is at ", mo_hp, "Hit Points"
            print "You did ", my_dmg, "damage!"
            print
            my_hp = my_hp - mo_dmg
            print "I was attacked by the lk for ", mo_dmg," damage!"
            print "My Hit Points are ", my_hp
            print
        elif choice == 2:
            mo_hp = mo_hp - my_dmg / 2
            print "The Lich King is at", mo_hp, "Hit Points"
            print "you did ", my_dmg / 2, "damage!"
            print
            my_hp = my_hp - mo_dmg
            print "I was attacked by the lk for ", mo_dmg," damage!"
            print "My Hit Points are ", my_hp
            print
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100730/3b563fa7/attachment.html>

From smokefloat at gmail.com  Sat Jul 31 05:03:27 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 30 Jul 2010 23:03:27 -0400
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTinS5izbK9Lx_diMWT2d8DjW+4Bn8JpwHBShNRqU@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
	<AANLkTimaLJ03EXXE7+yPUGq51KXn-V5KYR6WECBirJwT@mail.gmail.com>
	<AANLkTimxKVxL0=rpiCACPANB1fd_0E_uL5Ck_JtxRMQ1@mail.gmail.com>
	<AANLkTikbC8jbiYqzisSNzJtH+wtwrg_xk4h4zhMU6+nt@mail.gmail.com>
	<AANLkTinsLf6AcPECY4UMyfXiYdX0+tzerFiTveXNXm+A@mail.gmail.com>
	<AANLkTinS5izbK9Lx_diMWT2d8DjW+4Bn8JpwHBShNRqU@mail.gmail.com>
Message-ID: <AANLkTi=y6nKvSjvND+1VK6BRGFTagGrbvTYUdVxZRP7m@mail.gmail.com>

On Fri, Jul 30, 2010 at 10:44 PM, David Hutto <smokefloat at gmail.com> wrote:
> On Fri, Jul 30, 2010 at 10:43 PM, David Hutto <smokefloat at gmail.com> wrote:
>> On Fri, Jul 30, 2010 at 10:25 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
>>> On Fri, Jul 30, 2010 at 17:43, David Hutto <smokefloat at gmail.com> wrote:
>>>> This is the url:
>>>> http://python.pastebin.com/fP3jjqGj
>>>
>>> This is a slight revision, with my suggested changes highlighted:
>>> <http://python.pastebin.com/uFznsUYZ>
>>>
>>> Dick Moores
>>>
>>
>> http://python.pastebin.com/auw36h87
>>
>
> Maybe this time gmail will post the link, it keeps showing blank when I send::
> http://pastebin.com/auw36h87
>


This fixes the floating point 'bug' when numerator is greater than denominator:
http://python.pastebin.com/bJ5UzsBE

From smokefloat at gmail.com  Sat Jul 31 05:25:51 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 30 Jul 2010 23:25:51 -0400
Subject: [Tutor] Python - RPG Combat System
In-Reply-To: <AANLkTi=N41TC-6qSqhD1CGwBV+q61L92Rg_zdNp=1m-_@mail.gmail.com>
References: <AANLkTi=N41TC-6qSqhD1CGwBV+q61L92Rg_zdNp=1m-_@mail.gmail.com>
Message-ID: <AANLkTikbTe7uRSWHgTMBmgLE2Kx0bF6MS-TWS1xzhH6c@mail.gmail.com>

On Fri, Jul 30, 2010 at 10:49 PM, Jason MacFiggen <jmacfiggen at gmail.com> wrote:
> I am have trouble figuring out how to make my program stop at 0 hit
> points.... if I run it, it always goes into the negative hitpoints...
>
> So my question is how do I make this program end at exactly 0 hit points
> every time instead of going over?
>
> and also, what can I do instead of writing print so many times?
>
> import random
> ??? my_hp = 50
> ??? mo_hp = 50
> ??? my_dmg = random.randrange(1, 20)
> ??? mo_dmg = random.randrange(1, 20)

You ask for a random number

> ??? while True:
> ??????? if mo_hp < 0:
> ??????????? print "The Lich King has been slain!"
> ??????? elif my_hp < 0:
> ??????????? print "You have been slain by the Lich King!"
> ??????? if mo_hp <= 0:
> ??????????? break
> ??????? elif my_hp <= 0:
> ??????????? break
> ??????? else:
> ??????????? print "Menu Selections: "
> ??????????? print "1 - Attack"
> ??????????? print "2 - Defend"
> ??????????? print
> ??????????? choice = input ("Enter your selection. ")
> ??????????? choice = float(choice)
> ??????????? print
> ??????? if choice == 1:
> ??????????? mo_hp = mo_hp - my_dmg
> ??????????? print "The Lich King is at ", mo_hp, "Hit Points"
> ??????????? print "You did ", my_dmg, "damage!"
> ??????????? print
> ??????????? my_hp = my_hp - mo_dmg
> ??????????? print "I was attacked by the lk for ", mo_dmg," damage!"
> ??????????? print "My Hit Points are ", my_hp
> ??????????? print
> ??????? elif choice == 2:
> ??????????? mo_hp = mo_hp - my_dmg / 2
> ??????????? print "The Lich King is at", mo_hp, "Hit Points"
> ??????????? print "you did ", my_dmg / 2, "damage!"
> ??????????? print

Then you your points by that random number, so if the random
subtracted from current hp is negative it will print that negative
when you ask it to print hp - mydmg.

So, you add another if hp <= 0, in addition to the if my mydmg>myhp,
then print 0, instead of hp - myd_mg

> ??????????? my_hp = my_hp - mo_dmg
> ??????????? print "I was attacked by the lk for ", mo_dmg," damage!"
> ??????????? print "My Hit Points are ", my_hp
> ??????????? print
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

From steve at pearwood.info  Sat Jul 31 05:51:55 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 31 Jul 2010 13:51:55 +1000
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTi=y6nKvSjvND+1VK6BRGFTagGrbvTYUdVxZRP7m@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
	<AANLkTinS5izbK9Lx_diMWT2d8DjW+4Bn8JpwHBShNRqU@mail.gmail.com>
	<AANLkTi=y6nKvSjvND+1VK6BRGFTagGrbvTYUdVxZRP7m@mail.gmail.com>
Message-ID: <201007311351.56747.steve@pearwood.info>

On Sat, 31 Jul 2010 01:03:27 pm David Hutto wrote:

> This fixes the floating point 'bug' when numerator is greater than
> denominator: http://python.pastebin.com/bJ5UzsBE

I don't mean to be disparaging ... ah hell, who am I fooling? Yes I do. 
What is that mess? *wink*

I can see at least four problems with that:

1. You have a function called "gcd" that doesn't calculate the gcd, but 
does something else as well. That makes it a misleading name. 

2. The principles of code reuse and encapsulation suggest that each 
function should (as much as possible) do one thing, and do it well. You 
have a function that tries to do two or three things. You should have a 
single function to calculate the gcd, and a second function to use the 
gcd for reducing a fraction as needed, and potentially a third function 
to report the results to the user.

3. Your function has a serious bug. To see it, call gcd(5, 5) and see 
what it doesn't do.

4. Code duplication. Your function repeats fairly major chunks of code. 
Copy-and-paste programming is one of the Deadly Sins for programmers. 
The way to get rid of that is by encapsulating code in functions (see 
point 1 above).



-- 
Steven D'Aprano

From jmacfiggen at gmail.com  Sat Jul 31 06:00:26 2010
From: jmacfiggen at gmail.com (Jason MacFiggen)
Date: Fri, 30 Jul 2010 21:00:26 -0700
Subject: [Tutor] Simple Python Program
Message-ID: <AANLkTimoOejxLXBcYAsqjRS39OSvSLcWiFz=gTQ3N1Am@mail.gmail.com>

Can anyone tell me how to fix the errors I am getting if possible? I'm quite
new and so confused...

also how do I display the winner under the displayInfo function?

import random

def main():
    print

    playerOne, playerTwo = inputNames(playerOne, PlayerTwo)

    while endProgram == 'no':

        endProgram == no
        playerOne = 'NO NAME'
        playerTwo = 'NO NAME'

        winnerName = rollDice(p1number, p2number, playerOne, playerTwo,
winnerName)
        winnerName = displayInfo

        endProgram = raw_input('Do you want to end program? (Enter yes or
no): ')

def inputNames(playerOne, PlayerTwo):

    p1name = raw_input("Enter your name.")
    p2name = raw_input("Enter your name.")
    return playerOne, playerTwo

def random(winnerName):

    p1number = random.randint(1, 6)
    p2number = random.randint(1, 6)

    if p1number > p2number:
        playerOne = winnerName
    elif p1number < p2number:
        playerTwo = winnerName
    else p1number == p2number:
        playerOne, playerTwo = winnerName

def displayInfo():

    #how do I display winner?

main()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100730/ae8b2981/attachment.html>

From steve at pearwood.info  Sat Jul 31 06:00:35 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 31 Jul 2010 14:00:35 +1000
Subject: [Tutor] Python - RPG Combat System
In-Reply-To: <AANLkTi=N41TC-6qSqhD1CGwBV+q61L92Rg_zdNp=1m-_@mail.gmail.com>
References: <AANLkTi=N41TC-6qSqhD1CGwBV+q61L92Rg_zdNp=1m-_@mail.gmail.com>
Message-ID: <201007311400.35706.steve@pearwood.info>

On Sat, 31 Jul 2010 12:49:36 pm Jason MacFiggen wrote:
> I am have trouble figuring out how to make my program stop at 0 hit
> points.... if I run it, it always goes into the negative hitpoints...
>
> So my question is how do I make this program end at exactly 0 hit
> points every time instead of going over?

I don't have much time to work on this now, but you should do something 
like:

while mo_hp > 0 or my_hp > 0:  
    # combat stops when either combatant is dead
    do_combat_round()
    if mo_hp <= 0:
? ? ? ? print "The Lich King has been slain!"
? ? if my_hp <= 0:
? ? ? ? print "You have been slain by the Lich King!"


> and also, what can I do instead of writing print so many times?

Don't write print so many times.

I don't understand the question. If you want to print 20 things, then 
you have to print 20 things. If that's too much printing, then only 
print 10 of them :)

I suppose you could lump two or three things together, in one call to 
print, by adding your own newlines into the strings. E.g. instead of

print "Menu Selections: "
print "1 - Attack"
print "2 - Defend"
print

you could write:

print "Menu Selections: \n1 - Attack\n2 - Defend\n\n"

but I don't really see that as an advantage. Probably better to wrap 
common code into a function, then call the function:

def print_menu():
    print "Menu Selections: "
    print "1 - Attack"
    print "2 - Defend"
    print

print_menu()
choice = choose_from_menu()

etc.


-- 
Steven D'Aprano

From smokefloat at gmail.com  Sat Jul 31 06:37:49 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 31 Jul 2010 00:37:49 -0400
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <201007311351.56747.steve@pearwood.info>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
	<AANLkTinS5izbK9Lx_diMWT2d8DjW+4Bn8JpwHBShNRqU@mail.gmail.com>
	<AANLkTi=y6nKvSjvND+1VK6BRGFTagGrbvTYUdVxZRP7m@mail.gmail.com>
	<201007311351.56747.steve@pearwood.info>
Message-ID: <AANLkTi=b=vasQ2RD+n-YGSurHMYkUdDeL+gbN8ELDkqC@mail.gmail.com>

On Fri, Jul 30, 2010 at 11:51 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, 31 Jul 2010 01:03:27 pm David Hutto wrote:
>
>> This fixes the floating point 'bug' when numerator is greater than
>> denominator: http://python.pastebin.com/bJ5UzsBE
>
> I don't mean to be disparaging ... ah hell, who am I fooling? Yes I do.
> What is that mess? *wink*
It works except under [3], and that's fixable. And even, I know it's a
good gradumacated the eighth grade, newbie attempt.*winks* back.
>
> I can see at least four problems with that:
>
> 1. You have a function called "gcd" that doesn't calculate the gcd, but
> does something else as well. That makes it a misleading name.

I still have the habit of wanting to use the functions like I would an
instance of the functions.

>
> 2. The principles of code reuse and encapsulation suggest that each
> function should (as much as possible) do one thing, and do it well. You
> have a function that tries to do two or three things. You should have a
> single function to calculate the gcd, and a second function to use the
> gcd for reducing a fraction as needed, and potentially a third function
> to report the results to the user.

Then maybe I should have done a larger class of functions instead then?


>
> 3. Your function has a serious bug. To see it, call gcd(5, 5) and see
> what it doesn't do.

I'll get to it, but it seems like I had that in the original, not the
revised, maybe not, but did all other test cases for it, other than
that



>
> 4. Code duplication. Your function repeats fairly major chunks of code.
> Copy-and-paste programming is one of the Deadly Sins for programmers.
> The way to get rid of that is by encapsulating code in functions (see
> point 1 above).

I thought about putting certain print statements in a function, as
well as seperating the gcd into a from fractions import *, with a
different parameter for each if the returning if placed it into the
called function, but it seemed a little *overkill*, when it worked
well within the single function, with a few parameters placed in
through an instance with input.

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

From smokefloat at gmail.com  Sat Jul 31 06:43:30 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 31 Jul 2010 00:43:30 -0400
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTi=b=vasQ2RD+n-YGSurHMYkUdDeL+gbN8ELDkqC@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
	<AANLkTinS5izbK9Lx_diMWT2d8DjW+4Bn8JpwHBShNRqU@mail.gmail.com>
	<AANLkTi=y6nKvSjvND+1VK6BRGFTagGrbvTYUdVxZRP7m@mail.gmail.com>
	<201007311351.56747.steve@pearwood.info>
	<AANLkTi=b=vasQ2RD+n-YGSurHMYkUdDeL+gbN8ELDkqC@mail.gmail.com>
Message-ID: <AANLkTi=TttOu4Hs=S_Qh6RXf7E7G2wEJCPHQb04pe=eM@mail.gmail.com>

On Sat, Jul 31, 2010 at 12:37 AM, David Hutto <smokefloat at gmail.com> wrote:
> On Fri, Jul 30, 2010 at 11:51 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> On Sat, 31 Jul 2010 01:03:27 pm David Hutto wrote:
>>
>>> This fixes the floating point 'bug' when numerator is greater than
>>> denominator: http://python.pastebin.com/bJ5UzsBE
>>
>> I don't mean to be disparaging ... ah hell, who am I fooling? Yes I do.
>> What is that mess? *wink*
> It works except under [3], and that's fixable. And even, I know it's a
> good gradumacated the eighth grade, newbie attempt.*winks* back.
>>
>> I can see at least four problems with that:
>>
>> 1. You have a function called "gcd" that doesn't calculate the gcd, but
>> does something else as well. That makes it a misleading name.
>
> I still have the habit of wanting to use the functions like I would an
> instance of the functions.
>
>>
>> 2. The principles of code reuse and encapsulation suggest that each
>> function should (as much as possible) do one thing, and do it well. You
>> have a function that tries to do two or three things. You should have a
>> single function to calculate the gcd, and a second function to use the
>> gcd for reducing a fraction as needed, and potentially a third function
>> to report the results to the user.
>
> Then maybe I should have done a larger class of functions instead then?
>
>
>>
>> 3. Your function has a serious bug. To see it, call gcd(5, 5) and see
>> what it doesn't do.
>
> I'll get to it, but it seems like I had that in the original, not the
> revised, maybe not, but did all other test cases for it, other than
> that
>
>
>
>>
>> 4. Code duplication. Your function repeats fairly major chunks of code.
>> Copy-and-paste programming is one of the Deadly Sins for programmers.
>> The way to get rid of that is by encapsulating code in functions (see
>> point 1 above).
>
> I thought about putting certain print statements in a function, as
> well as seperating the gcd into a from fractions import *, with a
> different parameter for each if the returning if placed it into the
> called function, but it seemed a little *overkill*, when it worked
> well within the single function, with a few parameters placed in
> through an instance with input.
>
>>
>>
>>
>> --
>> Steven D'Aprano
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>

But, just to say, it started out as just trying to calculate the GCD
with your current python skills(not import fractions, and
print(gcd(3,9))for a practice exercise, and the rest is just the
input, and stated output.

From smokefloat at gmail.com  Sat Jul 31 09:39:10 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 31 Jul 2010 03:39:10 -0400
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTi=TttOu4Hs=S_Qh6RXf7E7G2wEJCPHQb04pe=eM@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
	<AANLkTinS5izbK9Lx_diMWT2d8DjW+4Bn8JpwHBShNRqU@mail.gmail.com>
	<AANLkTi=y6nKvSjvND+1VK6BRGFTagGrbvTYUdVxZRP7m@mail.gmail.com>
	<201007311351.56747.steve@pearwood.info>
	<AANLkTi=b=vasQ2RD+n-YGSurHMYkUdDeL+gbN8ELDkqC@mail.gmail.com>
	<AANLkTi=TttOu4Hs=S_Qh6RXf7E7G2wEJCPHQb04pe=eM@mail.gmail.com>
Message-ID: <AANLkTik9L3odxZE7NvS6SuSx1cK1EG+1PBCRZJwVd7X3@mail.gmail.com>

On Sat, Jul 31, 2010 at 12:43 AM, David Hutto <smokefloat at gmail.com> wrote:
> On Sat, Jul 31, 2010 at 12:37 AM, David Hutto <smokefloat at gmail.com> wrote:
>> On Fri, Jul 30, 2010 at 11:51 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>>> On Sat, 31 Jul 2010 01:03:27 pm David Hutto wrote:
>>>
>>>> This fixes the floating point 'bug' when numerator is greater than
>>>> denominator: http://python.pastebin.com/bJ5UzsBE
>>>
>>> I don't mean to be disparaging ... ah hell, who am I fooling? Yes I do.
>>> What is that mess? *wink*
>> It works except under [3], and that's fixable. And even, I know it's a
>> good gradumacated the eighth grade, newbie attempt.*winks* back.
>>>
>>> I can see at least four problems with that:
>>>
>>> 1. You have a function called "gcd" that doesn't calculate the gcd, but
>>> does something else as well. That makes it a misleading name.
>>
>> I still have the habit of wanting to use the functions like I would an
>> instance of the functions.
>>
>>>
>>> 2. The principles of code reuse and encapsulation suggest that each
>>> function should (as much as possible) do one thing, and do it well. You
>>> have a function that tries to do two or three things. You should have a
>>> single function to calculate the gcd, and a second function to use the
>>> gcd for reducing a fraction as needed, and potentially a third function
>>> to report the results to the user.
>>
>> Then maybe I should have done a larger class of functions instead then?
>>
>>
>>>
>>> 3. Your function has a serious bug. To see it, call gcd(5, 5) and see
>>> what it doesn't do.
>>
>> I'll get to it, but it seems like I had that in the original, not the
>> revised, maybe not, but did all other test cases for it, other than
>> that
>>
>>
>>
>>>
>>> 4. Code duplication. Your function repeats fairly major chunks of code.
>>> Copy-and-paste programming is one of the Deadly Sins for programmers.
>>> The way to get rid of that is by encapsulating code in functions (see
>>> point 1 above).
>>
>> I thought about putting certain print statements in a function, as
>> well as seperating the gcd into a from fractions import *, with a
>> different parameter for each if the returning if placed it into the
>> called function, but it seemed a little *overkill*, when it worked
>> well within the single function, with a few parameters placed in
>> through an instance with input.
>>
>>>
>>>
>>>
>>> --
>>> Steven D'Aprano
>>> _______________________________________________
>>> Tutor maillist ?- ?Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>
>
> But, just to say, it started out as just trying to calculate the GCD
> with your current python skills(not import fractions, and
> print(gcd(3,9))for a practice exercise, and the rest is just the
> input, and stated output.
>

however, had it been a math exercise, I would have sucked in boiling
it down, initially.

From coolankur2006 at gmail.com  Sat Jul 31 09:50:22 2010
From: coolankur2006 at gmail.com (ANKUR AGGARWAL)
Date: Sat, 31 Jul 2010 13:20:22 +0530
Subject: [Tutor] string editing
Message-ID: <AANLkTin8yLVKO5=vK2bYHNh23YhGL9gjTN4f0xF5C0Oy@mail.gmail.com>

hey although i knw string are mutable but i want to know if there is anyway
to add in the string.
like i m wrking on the tool and want to run the input from the user in the
terminal

like user makes input "this is ankur"
and i want it like "this\ is\ ankur"  ???????
is it possible??
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100731/c8ce060f/attachment.html>

From breamoreboy at yahoo.co.uk  Sat Jul 31 10:07:07 2010
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 31 Jul 2010 09:07:07 +0100
Subject: [Tutor] string editing
In-Reply-To: <AANLkTin8yLVKO5=vK2bYHNh23YhGL9gjTN4f0xF5C0Oy@mail.gmail.com>
References: <AANLkTin8yLVKO5=vK2bYHNh23YhGL9gjTN4f0xF5C0Oy@mail.gmail.com>
Message-ID: <i30ljj$pmu$1@dough.gmane.org>

On 31/07/2010 08:50, ANKUR AGGARWAL wrote:
> hey although i knw string are mutable but i want to know if there is anyway
                                ^^^ immutable!
> to add in the string.
> like i m wrking on the tool and want to run the input from the user in the
> terminal
>
> like user makes input "this is ankur"
> and i want it like "this\ is\ ankur"  ???????
> is it possible??
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

 >>> ankur = "this is ankur"
 >>> ankur.replace(' ', '\ ')
'this\\ is\\ ankur'

HTH.

Mark Lawrence.


From evert.rol at gmail.com  Sat Jul 31 10:50:13 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Sat, 31 Jul 2010 10:50:13 +0200
Subject: [Tutor] Simple Python Program
In-Reply-To: <AANLkTimoOejxLXBcYAsqjRS39OSvSLcWiFz=gTQ3N1Am@mail.gmail.com>
References: <AANLkTimoOejxLXBcYAsqjRS39OSvSLcWiFz=gTQ3N1Am@mail.gmail.com>
Message-ID: <F3329EE8-1312-4A63-B48E-491602225E92@gmail.com>

> Can anyone tell me how to fix the errors I am getting if possible? I'm quite new and so confused...

You're not telling us what the errors are. If you'd like us help to debug your program, best is to provide information about how you run it, and what output you're getting. Not just the program (sure, we can all copy-paste the program and run it, but we're not all going to do that). Just copy-paste the error message along with the rest of the email a next time.
Python is pretty verbose and clear with its error messages; once you learn to read the traceback (bottom-up), you can often figure out what's wrong: read the exact error message and line number, and try to understand why you get that message.

That said, I can see one glaring error when skimming through your code (unless I'm horribly misreading things):
 
>  import random
> def main():
>     print
> 
>     playerOne, playerTwo = inputNames(playerOne, PlayerTwo)
>      
>     while endProgram == 'no':

You use endProgram to compare with 'no' here, but
> 
>         endProgram == no

you only set the variable here.

This is programming 101 (not even Python specific): declare (& set) your variables before you use them (in comparisons, function calls, etc).

Also:
>         playerOne = 'NO NAME'
>         playerTwo = 'NO NAME'

are set here to 'NO NAME' (some default value), but *before* that, you assign real names. Since the default assignment is after the proper assignment, you end up with 'NO NAME' for both players (except that your program currently crashes at the while statement).

Finally:
> 
> also how do I display the winner under the displayInfo function?
 
If you want to do that, you'll have to feed the displayInfo() function the name of the winner as an argument.
What you do below in the second line, is assign the displayInfo function to winnerName. Instead, you'll have to call that function, with the winnerName as as argument (you're doing this correctly before, so it's somewhat odd you're doing it wrong here).

>         winnerName = rollDice(p1number, p2number, playerOne, playerTwo, winnerName)
>         winnerName = displayInfo

All in all, I can see why you're "so confused". Do you understand what you're doing; specifically, do you understand the flow of the program? Or did you just copy-paste something and made a few edits, then gave it a try? 
Perhaps you should take a step back, start even a bit smaller (single function programs), read a few other tutorials, then come back to this program.
You're most welcome to ask questions here, but looking through your code, there's a few generic programming mistakes here that you should learn about first.

Good luck,

  Evert


>         endProgram = raw_input('Do you want to end program? (Enter yes or no): ')
> 
> def inputNames(playerOne, PlayerTwo):
> 
>     p1name = raw_input("Enter your name.")
>     p2name = raw_input("Enter your name.")
>     return playerOne, playerTwo
> 
> def random(winnerName):
> 
>     p1number = random.randint(1, 6)
>     p2number = random.randint(1, 6)
> 
>     if p1number > p2number:
>         playerOne = winnerName
>     elif p1number < p2number:
>         playerTwo = winnerName
>     else p1number == p2number:
>         playerOne, playerTwo = winnerName
>         
> def displayInfo():
> 
>     #how do I display winner?
>     
> main()
> 


From alan.gauld at btinternet.com  Sat Jul 31 11:27:51 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 31 Jul 2010 10:27:51 +0100
Subject: [Tutor] string editing
References: <AANLkTin8yLVKO5=vK2bYHNh23YhGL9gjTN4f0xF5C0Oy@mail.gmail.com>
Message-ID: <i30qao$5ap$1@dough.gmane.org>


"ANKUR AGGARWAL" <coolankur2006 at gmail.com> wrote

> hey although i knw string are mutable but i want to know if there is 
> anyway
> to add in the string.

Although strings are immutable there are numerous ways to create a new
variation on a string. For your purposes the replace() method is 
probably
best but if you do

>>> help(str)

you can read about all the options.

You might also find the Handling Text topic of my tutorial helpful.

HTH,


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




From smokefloat at gmail.com  Sat Jul 31 12:06:28 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 31 Jul 2010 06:06:28 -0400
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTik9L3odxZE7NvS6SuSx1cK1EG+1PBCRZJwVd7X3@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com>
	<AANLkTinS5izbK9Lx_diMWT2d8DjW+4Bn8JpwHBShNRqU@mail.gmail.com>
	<AANLkTi=y6nKvSjvND+1VK6BRGFTagGrbvTYUdVxZRP7m@mail.gmail.com>
	<201007311351.56747.steve@pearwood.info>
	<AANLkTi=b=vasQ2RD+n-YGSurHMYkUdDeL+gbN8ELDkqC@mail.gmail.com>
	<AANLkTi=TttOu4Hs=S_Qh6RXf7E7G2wEJCPHQb04pe=eM@mail.gmail.com>
	<AANLkTik9L3odxZE7NvS6SuSx1cK1EG+1PBCRZJwVd7X3@mail.gmail.com>
Message-ID: <AANLkTi=cS+0pcBcT9eYZ-0zGRz4juKTYdsnmz8m=QpFT@mail.gmail.com>

On Sat, Jul 31, 2010 at 3:39 AM, David Hutto <smokefloat at gmail.com> wrote:
> On Sat, Jul 31, 2010 at 12:43 AM, David Hutto <smokefloat at gmail.com> wrote:
>> On Sat, Jul 31, 2010 at 12:37 AM, David Hutto <smokefloat at gmail.com> wrote:
>>> On Fri, Jul 30, 2010 at 11:51 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>>>> On Sat, 31 Jul 2010 01:03:27 pm David Hutto wrote:
>>>>
>>>>> This fixes the floating point 'bug' when numerator is greater than
>>>>> denominator: http://python.pastebin.com/bJ5UzsBE
>>>>
>>>> I don't mean to be disparaging ... ah hell, who am I fooling? Yes I do.
>>>> What is that mess? *wink*
>>> It works except under [3], and that's fixable. And even, I know it's a
>>> good gradumacated the eighth grade, newbie attempt.*winks* back.
>>>>
>>>> I can see at least four problems with that:
>>>>
>>>> 1. You have a function called "gcd" that doesn't calculate the gcd, but
>>>> does something else as well. That makes it a misleading name.
>>>
>>> I still have the habit of wanting to use the functions like I would an
>>> instance of the functions.
>>>
>>>>
>>>> 2. The principles of code reuse and encapsulation suggest that each
>>>> function should (as much as possible) do one thing, and do it well. You
>>>> have a function that tries to do two or three things. You should have a
>>>> single function to calculate the gcd, and a second function to use the
>>>> gcd for reducing a fraction as needed, and potentially a third function
>>>> to report the results to the user.
>>>
>>> Then maybe I should have done a larger class of functions instead then?
>>>
>>>
>>>>
>>>> 3. Your function has a serious bug. To see it, call gcd(5, 5) and see
>>>> what it doesn't do.
>>>
>>> I'll get to it, but it seems like I had that in the original, not the
>>> revised, maybe not, but did all other test cases for it, other than
>>> that
>>>
>>>
>>>
>>>>
>>>> 4. Code duplication. Your function repeats fairly major chunks of code.
>>>> Copy-and-paste programming is one of the Deadly Sins for programmers.
>>>> The way to get rid of that is by encapsulating code in functions (see
>>>> point 1 above).
>>>
>>> I thought about putting certain print statements in a function, as
>>> well as seperating the gcd into a from fractions import *, with a
>>> different parameter for each if the returning if placed it into the
>>> called function, but it seemed a little *overkill*, when it worked
>>> well within the single function, with a few parameters placed in
>>> through an instance with input.
>>>
>>>>
>>>>
>>>>
>>>> --
>>>> Steven D'Aprano
>>>> _______________________________________________
>>>> Tutor maillist ?- ?Tutor at python.org
>>>> To unsubscribe or change subscription options:
>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>
>>>
>>
>> But, just to say, it started out as just trying to calculate the GCD
>> with your current python skills(not import fractions, and
>> print(gcd(3,9))for a practice exercise, and the rest is just the
>> input, and stated output.
>>
>
> however, had it been a math exercise, I would have sucked in boiling
> it down, initially.
>

There is a difference between defining a function as a singular
activity needed to be performed, and a function that serves as a tool,
that asks for input and output, as well as serves several
utilizations, e.g., it not only accepts the numerator/denominator, but
spits out the gcd, the reduced, and the whole numeber reduced if the
numerator is greater. but if they are even, will come with a little if
num == den boolean, when I'm finished .

From rdmoores at gmail.com  Sat Jul 31 12:15:26 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 31 Jul 2010 03:15:26 -0700
Subject: [Tutor] problem with simple script
In-Reply-To: <AANLkTinjEg+42QwGVzu4wCwuKih5vJ_PM94GPaVetHCs@mail.gmail.com>
References: <AANLkTinZmDNsjLKHARq6-gyTKuaOPZHh-wyHOzi5TtKB@mail.gmail.com> 
	<AANLkTineFewgmvgA04LHL2BZU7yHg_Fe5_xt5xVyMsj0@mail.gmail.com> 
	<AANLkTinjEg+42QwGVzu4wCwuKih5vJ_PM94GPaVetHCs@mail.gmail.com>
Message-ID: <AANLkTimkce40SeN6QiwCPe0dGke2rb+QeftaPymo4sjE@mail.gmail.com>

On Thu, Jul 29, 2010 at 12:22, Richard D. Moores <rdmoores at gmail.com> wrote:
> On Wed, Jul 28, 2010 at 08:35, Richard D. Moores <rdmoores at gmail.com> wrote:
>
> Here's my slight revision of Steven's script (see my note, lines 9-14)
> -- revised only because I wanted it to handle the case where the user
> (me) entered the interval bounds in the wrong order, e.g., 10, 5
> instead of 5, 10. ?I've also added a way ('r') for the user to choose
> to get another random number in the same interval without having to
> reenter the bounds: <http://tutoree7.pastebin.com/XZ2Eek4Z>. Then I
> needed a way ('c') to choose to change the bounds after 'r' had been
> used. I used a flag (lines 42, 53, 55) to accomplish these additions.
> Was there a better way? Should I have written a couple of extra
> functions instead of using the flag? Are flags unpythonic?

So here I am talking to myself again. :)

Well, whether flags are unpythonic or not, I was finally able to get
rid of them. See <http://tutoree7.pastebin.com/qYVnhphx>

Dick

From rdmoores at gmail.com  Sat Jul 31 12:44:29 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 31 Jul 2010 03:44:29 -0700
Subject: [Tutor] A better way for greatest common divisor
In-Reply-To: <AANLkTi=cS+0pcBcT9eYZ-0zGRz4juKTYdsnmz8m=QpFT@mail.gmail.com>
References: <AANLkTik4MdixwS2pZSUrWB3PW4XhjocgBZnSga+ySM0Y@mail.gmail.com> 
	<AANLkTinS5izbK9Lx_diMWT2d8DjW+4Bn8JpwHBShNRqU@mail.gmail.com> 
	<AANLkTi=y6nKvSjvND+1VK6BRGFTagGrbvTYUdVxZRP7m@mail.gmail.com> 
	<201007311351.56747.steve@pearwood.info>
	<AANLkTi=b=vasQ2RD+n-YGSurHMYkUdDeL+gbN8ELDkqC@mail.gmail.com> 
	<AANLkTi=TttOu4Hs=S_Qh6RXf7E7G2wEJCPHQb04pe=eM@mail.gmail.com> 
	<AANLkTik9L3odxZE7NvS6SuSx1cK1EG+1PBCRZJwVd7X3@mail.gmail.com> 
	<AANLkTi=cS+0pcBcT9eYZ-0zGRz4juKTYdsnmz8m=QpFT@mail.gmail.com>
Message-ID: <AANLkTik01HvLN0itFRRqdF+CpEKeNQ3YWLXo=UJDWA3g@mail.gmail.com>

>> On Sat, 31 Jul 2010 01:03:27 pm David Hutto wrote:

> There is a difference between defining a function as a singular
> activity needed to be performed, and a function that serves as a tool,
> that asks for input and output, as well as serves several
> utilizations, e.g., it not only accepts the numerator/denominator, but
> spits out the gcd, the reduced, and the whole numeber reduced if the
> numerator is greater. but if they are even, will come with a little if
> num == den boolean, when I'm finished .

Of course you can do as you wish, but how about breaking up that
function as Steven suggests, and using the script, the module that
contains them as the tool you desired?

Dick

From quasipedia at gmail.com  Sat Jul 31 13:22:40 2010
From: quasipedia at gmail.com (Mac Ryan)
Date: Sat, 31 Jul 2010 13:22:40 +0200
Subject: [Tutor] problem with subprocess
In-Reply-To: <AANLkTi=F4hfB6ZaWxQ=grYZPJNN0yg3eeRotrc7e4cXf@mail.gmail.com>
References: <AANLkTi=F4hfB6ZaWxQ=grYZPJNN0yg3eeRotrc7e4cXf@mail.gmail.com>
Message-ID: <1280575360.3357.12.camel@jabbar>

On Fri, 2010-07-30 at 14:36 +0200, Bala subramanian wrote:
> I have to do a series of job in a remote machine. I put each job in a
> text file called 'job' as and wrote the following code that can read
> each line in the text file and execute the job.

If that works for you, no need to change it, of course. 

Just wondered - however - if you are aware that there is a python
library that just do that (remote machine management). It's called
"fabric":

>From the official docs: "Fabric is a Python library and command-line
tool for streamlining the use of SSH for application deployment or
systems administration tasks.

It provides a basic suite of operations for executing local or remote
shell commands (normally or via sudo) and uploading/downloading files,
as well as auxiliary functionality such as prompting the running user
for input, or aborting execution.

Typical use involves creating a Python module containing one or more
functions, then executing them via the fab command-line tool."

http://docs.fabfile.org/0.9.1/




From bgailer at gmail.com  Sat Jul 31 19:51:26 2010
From: bgailer at gmail.com (bob gailer)
Date: Sat, 31 Jul 2010 13:51:26 -0400
Subject: [Tutor] Python - RPG Combat System
In-Reply-To: <AANLkTi=N41TC-6qSqhD1CGwBV+q61L92Rg_zdNp=1m-_@mail.gmail.com>
References: <AANLkTi=N41TC-6qSqhD1CGwBV+q61L92Rg_zdNp=1m-_@mail.gmail.com>
Message-ID: <4C54629E.7070901@gmail.com>

On 7/30/2010 10:49 PM, Jason MacFiggen wrote:
> what can I do instead of writing print so many times?
> import random
>     my_hp = 50
>     mo_hp = 50
>     my_dmg = random.randrange(1, 20)
>     mo_dmg = random.randrange(1, 20)
>     while True:
>         if mo_hp < 0:
>             print "The Lich King has been slain!"
>         elif my_hp < 0:
>             print "You have been slain by the Lich King!"
>         if mo_hp <= 0:
>             break
>         elif my_hp <= 0:
>             break
>         else:
>             print "Menu Selections: "
>             print "1 - Attack"
>             print "2 - Defend"
>             print
>             choice = input ("Enter your selection. ")
>             choice = float(choice)
>             print
>         if choice == 1:
>             mo_hp = mo_hp - my_dmg
>             print "The Lich King is at ", mo_hp, "Hit Points"
>             print "You did ", my_dmg, "damage!"
>             print
>             my_hp = my_hp - mo_dmg
>             print "I was attacked by the lk for ", mo_dmg," damage!"
>             print "My Hit Points are ", my_hp
>             print
>         elif choice == 2:
>             mo_hp = mo_hp - my_dmg / 2
>             print "The Lich King is at", mo_hp, "Hit Points"
>             print "you did ", my_dmg / 2, "damage!"
>             print
>             my_hp = my_hp - mo_dmg
>             print "I was attacked by the lk for ", mo_dmg," damage!"
>             print "My Hit Points are ", my_hp
>             print

Most of the statements in each choice block are identical. Factor them 
out, giving:

         if choice == 1:
             mo_hp = mo_hp - my_dmg
             print "you did ", my_dmg /, "damage!"
         elif choice == 2:
             mo_hp = mo_hp - my_dmg / 2
             print "you did ", my_dmg / 2, "damage!"
         print "The Lich King is at", mo_hp, "Hit Points"
         my_hp = my_hp - mo_dmg
         print "You did ", my_dmg, "damage!"
         print
         print "I was attacked by the lk for ", mo_dmg," damage!"
         print "My Hit Points are ", my_hp
         print

You could (better) move these statements into a function, passing 1 or 2 
as the divisor for my_dmg and returning the updated values for my_ho and 
my_hp.

def update(factor):
     print "The Lich King is at", mo_hp, "Hit Points"
     print "you did ", my_dmg / factor, "damage!"
     print
     print "I was attacked by the lk for ", mo_dmg," damage!"
     print "My Hit Points are ", my_hp
     print
     return mo_hp - my_dmg / factor, my_hp - mo_dmg
...
         if choice == 1:
             mo_hp, my_hp = update(1)
         elif choice == 2:
             mo_hp, my_hp = update(2)

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From smokefloat at gmail.com  Sat Jul 31 20:04:30 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 31 Jul 2010 14:04:30 -0400
Subject: [Tutor] Python - RPG Combat System
In-Reply-To: <4C54629E.7070901@gmail.com>
References: <AANLkTi=N41TC-6qSqhD1CGwBV+q61L92Rg_zdNp=1m-_@mail.gmail.com>
	<4C54629E.7070901@gmail.com>
Message-ID: <AANLkTimFUJ8mENsVvRYHc4txkjkJaq+=9qGfHKr=m1eF@mail.gmail.com>

On Sat, Jul 31, 2010 at 1:51 PM, bob gailer <bgailer at gmail.com> wrote:
> On 7/30/2010 10:49 PM, Jason MacFiggen wrote:
>>
>> what can I do instead of writing print so many times?
>> import random
>> ? ?my_hp = 50
>> ? ?mo_hp = 50
>> ? ?my_dmg = random.randrange(1, 20)
>> ? ?mo_dmg = random.randrange(1, 20)
>> ? ?while True:
>> ? ? ? ?if mo_hp < 0:
>> ? ? ? ? ? ?print "The Lich King has been slain!"
>> ? ? ? ?elif my_hp < 0:
>> ? ? ? ? ? ?print "You have been slain by the Lich King!"
>> ? ? ? ?if mo_hp <= 0:
>> ? ? ? ? ? ?break
>> ? ? ? ?elif my_hp <= 0:
>> ? ? ? ? ? ?break
>> ? ? ? ?else:
>> ? ? ? ? ? ?print "Menu Selections: "
>> ? ? ? ? ? ?print "1 - Attack"
>> ? ? ? ? ? ?print "2 - Defend"
>> ? ? ? ? ? ?print
>> ? ? ? ? ? ?choice = input ("Enter your selection. ")
>> ? ? ? ? ? ?choice = float(choice)
>> ? ? ? ? ? ?print
>> ? ? ? ?if choice == 1:
>> ? ? ? ? ? ?mo_hp = mo_hp - my_dmg
>> ? ? ? ? ? ?print "The Lich King is at ", mo_hp, "Hit Points"
>> ? ? ? ? ? ?print "You did ", my_dmg, "damage!"
>> ? ? ? ? ? ?print
>> ? ? ? ? ? ?my_hp = my_hp - mo_dmg
>> ? ? ? ? ? ?print "I was attacked by the lk for ", mo_dmg," damage!"
>> ? ? ? ? ? ?print "My Hit Points are ", my_hp
>> ? ? ? ? ? ?print
>> ? ? ? ?elif choice == 2:
>> ? ? ? ? ? ?mo_hp = mo_hp - my_dmg / 2
>> ? ? ? ? ? ?print "The Lich King is at", mo_hp, "Hit Points"
>> ? ? ? ? ? ?print "you did ", my_dmg / 2, "damage!"
>> ? ? ? ? ? ?print
>> ? ? ? ? ? ?my_hp = my_hp - mo_dmg
>> ? ? ? ? ? ?print "I was attacked by the lk for ", mo_dmg," damage!"
>> ? ? ? ? ? ?print "My Hit Points are ", my_hp
>> ? ? ? ? ? ?print
>
> Most of the statements in each choice block are identical. Factor them out,
> giving:
>
> ? ? ? ?if choice == 1:
> ? ? ? ? ? ?mo_hp = mo_hp - my_dmg
> ? ? ? ? ? ?print "you did ", my_dmg /, "damage!"
> ? ? ? ?elif choice == 2:
> ? ? ? ? ? ?mo_hp = mo_hp - my_dmg / 2
> ? ? ? ? ? ?print "you did ", my_dmg / 2, "damage!"
> ? ? ? ?print "The Lich King is at", mo_hp, "Hit Points"
> ? ? ? ?my_hp = my_hp - mo_dmg
> ? ? ? ?print "You did ", my_dmg, "damage!"
> ? ? ? ?print
> ? ? ? ?print "I was attacked by the lk for ", mo_dmg," damage!"
> ? ? ? ?print "My Hit Points are ", my_hp
> ? ? ? ?print
>
> You could (better) move these statements into a function, passing 1 or 2 as
> the divisor for my_dmg and returning the updated values for my_ho

You mean my_dmg I think.

 and my_hp.
>
> def update(factor):
> ? ?print "The Lich King is at", mo_hp, "Hit Points"
> ? ?print "you did ", my_dmg / factor, "damage!"
> ? ?print
> ? ?print "I was attacked by the lk for ", mo_dmg," damage!"
> ? ?print "My Hit Points are ", my_hp
> ? ?print
> ? ?return mo_hp - my_dmg / factor, my_hp - mo_dmg
> ...
> ? ? ? ?if choice == 1:
> ? ? ? ? ? ?mo_hp, my_hp = update(1)
> ? ? ? ?elif choice == 2:
> ? ? ? ? ? ?mo_hp, my_hp = update(2)
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From ehamiter at gmail.com  Sat Jul 31 20:27:07 2010
From: ehamiter at gmail.com (Eric Hamiter)
Date: Sat, 31 Jul 2010 13:27:07 -0500
Subject: [Tutor] Writing scripts and apps for Internet consumption
Message-ID: <AANLkTi=FkworTTqE_1wXOyT3PMbHDV8giSkjnCNa7UDo@mail.gmail.com>

Not sure if this is the right place for this, since this is a tutor list,
but I think it is because it involves learning Python and the application of
knowledge.

I've just started learning it as my initial programming language as of two
months ago. I like to think I'm making steady progress, and I now understand
the most rudimentary level of the basics. What I keep reading is how Python
is most powerful on server side applications, in the cloud, so to speak. The
portability of Python is also widely evangelized.

Here's my problem with this so far-- I can write a basic script, have it
take in data, rearrange it, and spit it back out. Following along in a book,
I can write a basic GUI or game. It's all wine and roses on my Windows
laptop, where I have everything configured just right, with all of the
modules in place where they need to be.

Moving this to a server or even another computer so far has been a seemingly
impossible task. There's a lot of documentation for CGI scripting (which is
now frowned upon, with every page recommending looking into wsgi), and there
have been applications devoted to transforming scripts into Windows
executables (py2exe, etc.) but it seems like this is much more confusing
than need be, and I can't get them to work regardless. When I try and google
for solutions, choosing any terms like "web" or "server" point me to massive
framework solutions like Django or Pylons, which seem extraordinarily
complex for what I want.

Specific examples: I have a livewires/pygame GUI game I wrote along with
folowing the book "Python Programming for the Absolute Beginner" and it
works great on my laptop. I tried installing Python/pygame on a work
computer and copying my scripts over, but it endlessly fails with errors so
obtuse I can't troubleshoot. I'm not even sure if I have the correct modules
installed here. Should they be under "Lib" or "libs" or "includes"?  Trying
to use py2exe fails because I can't figure out how to include non-scripts in
the final program, like .pngs or .jpgs. How would I even begin to put this
on a server? I'm clueless.

Another program I am using on my laptop is a convenience script-- it takes
in a text list of groceries, and spits out a formatted list based on aisle
locations so I can get in and out of the grocery store faster. My laptop is
the only place I can use this. I've tried using multiple CGI examples, and
it always results in a "File Not Found" error. Not even sure how I can debug
it. I can have the server do a simple one-line of printing "Hello World" but
anything more complicated than that makes it implode.

The most frustrating thing is how flippantly experienced programmers say to
use Django for Python web apps because it's so simple to use. It took me a
good half-day to just install it, and unless I'm writing a sample code or if
I want to clone a newspaper service, I have absolutely no idea how I would
use it efficiently. I want to learn the basics before running off to learn a
new framework. I'm trying to find good resources so I can continue self
teaching, but everything I find seems to be tailored to two classes: the
complete newbie who doesn't know how to print a line, or an advanced
programmer who is using list comprehension within a recursion with multiple
modules.

In short, is there a "simple" method for putting python scripts onto a
server that I do not host myself? I've seen web2py and it looks like it
would be more my speed, but support is lacking and doesn't seem too
compatible with my host. I use Dreamhost, and they are very adaptable and
configurable, but so far I can't find an easy way to accomplish what I want.

Thanks for reading this far if you did! I welcome any suggestions
whatsoever.

Eric
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100731/1821f6a1/attachment.html>

From smokefloat at gmail.com  Sat Jul 31 20:34:55 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 31 Jul 2010 14:34:55 -0400
Subject: [Tutor] Writing scripts and apps for Internet consumption
In-Reply-To: <AANLkTi=FkworTTqE_1wXOyT3PMbHDV8giSkjnCNa7UDo@mail.gmail.com>
References: <AANLkTi=FkworTTqE_1wXOyT3PMbHDV8giSkjnCNa7UDo@mail.gmail.com>
Message-ID: <AANLkTinR44Gpb5U694s1QvEhZV7aVX8qMe_2_yMNBatK@mail.gmail.com>

On Sat, Jul 31, 2010 at 2:27 PM, Eric Hamiter <ehamiter at gmail.com> wrote:
> Not sure if this is the right place for this, since this is a tutor list,
> but I think it is because it involves learning Python and the application of
> knowledge.
>
> I've just started learning it as my initial programming language as of two
> months ago. I like to think I'm making steady progress, and I now understand
> the most rudimentary level of the basics. What I keep reading is how Python
> is most powerful on server side applications, in the cloud, so to speak. The
> portability of Python is also widely evangelized.
>
> Here's my problem with this so far-- I can write a basic script, have it
> take in data, rearrange it, and spit it back out. Following along in a book,
> I can write a basic GUI or game. It's all wine and roses on my Windows
> laptop, where I have everything configured just right, with all of the
> modules in place where they need to be.
>
> Moving this to a server or even another computer so far has been a seemingly
> impossible task. There's a lot of documentation for CGI scripting (which is
> now frowned upon, with every page recommending looking into wsgi), and there
> have been applications devoted to transforming scripts into Windows
> executables (py2exe, etc.) but it seems like this is much more confusing
> than need be, and I can't get them to work regardless. When I try and google
> for solutions, choosing any terms like "web" or "server" point me to massive
> framework solutions like Django or Pylons, which seem extraordinarily
> complex for what I want.
>
> Specific examples: I have a livewires/pygame GUI game I wrote along with
> folowing the book "Python Programming for the Absolute Beginner" and it
> works great on my laptop. I tried installing Python/pygame on a work
> computer and copying my scripts over, but it endlessly fails with errors so
> obtuse I can't troubleshoot. I'm not even sure if I have the correct modules
> installed here. Should they be under "Lib" or "libs" or "includes"?? Trying
> to use py2exe fails because I can't figure out how to include non-scripts in
> the final program, like .pngs or .jpgs. How would I even begin to put this
> on a server? I'm clueless.
>
> Another program I am using on my laptop is a convenience script-- it takes
> in a text list of groceries, and spits out a formatted list based on aisle
> locations so I can get in and out of the grocery store faster. My laptop is
> the only place I can use this. I've tried using multiple CGI examples, and
> it always results in a "File Not Found" error. Not even sure how I can debug
> it. I can have the server do a simple one-line of printing "Hello World" but
> anything more complicated than that makes it implode.
>
> The most frustrating thing is how flippantly experienced programmers say to
> use Django for Python web apps because it's so simple to use. It took me a
> good half-day to just install it, and unless I'm writing a sample code or if
> I want to clone a newspaper service, I have absolutely no idea how I would
> use it efficiently. I want to learn the basics before running off to learn a
> new framework. I'm trying to find good resources so I can continue self
> teaching, but everything I find seems to be tailored to two classes: the
> complete newbie who doesn't know how to print a line, or an advanced
> programmer who is using list comprehension within a recursion with multiple
> modules.
>
> In short, is there a "simple" method for putting python scripts onto a
> server that I do not host myself? I've seen web2py and it looks like it
> would be more my speed, but support is lacking and doesn't seem too
> compatible with my host. I use Dreamhost, and they are very adaptable and
> configurable, but so far I can't find an easy way to accomplish what I want.
>
> Thanks for reading this far if you did! I welcome any suggestions
> whatsoever.
>
> Eric
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

Get a linux hosting account, and a web address, most linux hosting
comes with python, so practice in the 'cloud'.

From bgailer at gmail.com  Sat Jul 31 20:35:03 2010
From: bgailer at gmail.com (bob gailer)
Date: Sat, 31 Jul 2010 14:35:03 -0400
Subject: [Tutor] Simple Python Program
In-Reply-To: <AANLkTimoOejxLXBcYAsqjRS39OSvSLcWiFz=gTQ3N1Am@mail.gmail.com>
References: <AANLkTimoOejxLXBcYAsqjRS39OSvSLcWiFz=gTQ3N1Am@mail.gmail.com>
Message-ID: <4C546CD7.5010207@gmail.com>

On 7/31/2010 12:00 AM, Jason MacFiggen wrote:
> Can anyone tell me how to fix the errors I am getting if possible? I'm 
> quite new and so confused...
I could give lots of diagnostic advice and detail. There is so much 
wrong with this program.

I suggest you discard it, back up and start with the simplest possible 
statement of the problem which is:
print a number randomly chosen from (0,1,2)

Then write the simplest possible program to do this one time; no loops 
or functions.
The entire program could then be written in 2 lines of code. Run it, fix 
it if it does not work. Once you have success -

Add (one at a time) various features:
- roll dice to select winner
- player names
- repetition

Continue to avoid writing functions. They are not necessary for such a 
simple program.

The final product will have less than 15 statements.

> also how do I display the winner under the displayInfo function?
> import random
>
> def main():
>     print
>
>     playerOne, playerTwo = inputNames(playerOne, PlayerTwo)
>
>     while endProgram == 'no':
>
>         endProgram == no
>         playerOne = 'NO NAME'
>         playerTwo = 'NO NAME'
>
>         winnerName = rollDice(p1number, p2number, playerOne, 
> playerTwo, winnerName)
>         winnerName = displayInfo
>
>         endProgram = raw_input('Do you want to end program? (Enter yes 
> or no): ')
>
> def inputNames(playerOne, PlayerTwo):
>
>     p1name = raw_input("Enter your name.")
>     p2name = raw_input("Enter your name.")
>     return playerOne, playerTwo
>
> def random(winnerName):
>
>     p1number = random.randint(1, 6)
>     p2number = random.randint(1, 6)
>
>     if p1number > p2number:
>         playerOne = winnerName
>     elif p1number < p2number:
>         playerTwo = winnerName
>     else p1number == p2number:
>         playerOne, playerTwo = winnerName
>
> def displayInfo():
>
>     #how do I display winner?
>
> main()
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>    


-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100731/fcf66ff4/attachment-0001.html>

From smokefloat at gmail.com  Sat Jul 31 20:37:04 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 31 Jul 2010 14:37:04 -0400
Subject: [Tutor] Writing scripts and apps for Internet consumption
In-Reply-To: <AANLkTinR44Gpb5U694s1QvEhZV7aVX8qMe_2_yMNBatK@mail.gmail.com>
References: <AANLkTi=FkworTTqE_1wXOyT3PMbHDV8giSkjnCNa7UDo@mail.gmail.com>
	<AANLkTinR44Gpb5U694s1QvEhZV7aVX8qMe_2_yMNBatK@mail.gmail.com>
Message-ID: <AANLkTinWB5mYOnXY5vY3=aRR0pyLo-67ieGx-Cx9Ccj-@mail.gmail.com>

On Sat, Jul 31, 2010 at 2:34 PM, David Hutto <smokefloat at gmail.com> wrote:
> On Sat, Jul 31, 2010 at 2:27 PM, Eric Hamiter <ehamiter at gmail.com> wrote:
>> Not sure if this is the right place for this, since this is a tutor list,
>> but I think it is because it involves learning Python and the application of
>> knowledge.
>>
>> I've just started learning it as my initial programming language as of two
>> months ago. I like to think I'm making steady progress, and I now understand
>> the most rudimentary level of the basics. What I keep reading is how Python
>> is most powerful on server side applications, in the cloud, so to speak. The
>> portability of Python is also widely evangelized.
>>
>> Here's my problem with this so far-- I can write a basic script, have it
>> take in data, rearrange it, and spit it back out. Following along in a book,
>> I can write a basic GUI or game. It's all wine and roses on my Windows
>> laptop, where I have everything configured just right, with all of the
>> modules in place where they need to be.
>>
>> Moving this to a server or even another computer so far has been a seemingly
>> impossible task. There's a lot of documentation for CGI scripting (which is
>> now frowned upon, with every page recommending looking into wsgi), and there
>> have been applications devoted to transforming scripts into Windows
>> executables (py2exe, etc.) but it seems like this is much more confusing
>> than need be, and I can't get them to work regardless. When I try and google
>> for solutions, choosing any terms like "web" or "server" point me to massive
>> framework solutions like Django or Pylons, which seem extraordinarily
>> complex for what I want.
>>
>> Specific examples: I have a livewires/pygame GUI game I wrote along with
>> folowing the book "Python Programming for the Absolute Beginner" and it
>> works great on my laptop. I tried installing Python/pygame on a work
>> computer and copying my scripts over, but it endlessly fails with errors so
>> obtuse I can't troubleshoot. I'm not even sure if I have the correct modules
>> installed here. Should they be under "Lib" or "libs" or "includes"?? Trying
>> to use py2exe fails because I can't figure out how to include non-scripts in
>> the final program, like .pngs or .jpgs. How would I even begin to put this
>> on a server? I'm clueless.
>>
>> Another program I am using on my laptop is a convenience script-- it takes
>> in a text list of groceries, and spits out a formatted list based on aisle
>> locations so I can get in and out of the grocery store faster. My laptop is
>> the only place I can use this. I've tried using multiple CGI examples, and
>> it always results in a "File Not Found" error. Not even sure how I can debug
>> it. I can have the server do a simple one-line of printing "Hello World" but
>> anything more complicated than that makes it implode.
>>
>> The most frustrating thing is how flippantly experienced programmers say to
>> use Django for Python web apps because it's so simple to use. It took me a
>> good half-day to just install it, and unless I'm writing a sample code or if
>> I want to clone a newspaper service, I have absolutely no idea how I would
>> use it efficiently. I want to learn the basics before running off to learn a
>> new framework. I'm trying to find good resources so I can continue self
>> teaching, but everything I find seems to be tailored to two classes: the
>> complete newbie who doesn't know how to print a line, or an advanced
>> programmer who is using list comprehension within a recursion with multiple
>> modules.
>>
>> In short, is there a "simple" method for putting python scripts onto a
>> server that I do not host myself? I've seen web2py and it looks like it
>> would be more my speed, but support is lacking and doesn't seem too
>> compatible with my host. I use Dreamhost, and they are very adaptable and
>> configurable, but so far I can't find an easy way to accomplish what I want.
>>
>> Thanks for reading this far if you did! I welcome any suggestions
>> whatsoever.
>>
>> Eric
>>
>>
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
> Get a linux hosting account, and a web address, most linux hosting
> comes with python, so practice in the 'cloud'.
>
 Some might argue that this would be a production server, so to speak,
but it's just for target practice, right?

From smokefloat at gmail.com  Sat Jul 31 20:44:40 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 31 Jul 2010 14:44:40 -0400
Subject: [Tutor] Simple Python Program
In-Reply-To: <4C546CD7.5010207@gmail.com>
References: <AANLkTimoOejxLXBcYAsqjRS39OSvSLcWiFz=gTQ3N1Am@mail.gmail.com>
	<4C546CD7.5010207@gmail.com>
Message-ID: <AANLkTim+pLpAk3nFaoUgCgmmaL3__LRBDOec69MbuYag@mail.gmail.com>

On Sat, Jul 31, 2010 at 2:35 PM, bob gailer <bgailer at gmail.com> wrote:
> On 7/31/2010 12:00 AM, Jason MacFiggen wrote:
>
> Can anyone tell me how to fix the errors I am getting if possible? I'm quite
> new and so confused...
>
>
> I could give lots of diagnostic advice and detail. There is so much wrong
> with this program.
>
> I suggest you discard it, back up and start with the simplest possible
> statement of the problem which is:
> print a number randomly chosen from (0,1,2)
>
> Then write the simplest possible program to do this one time; no loops or
> functions.
> The entire program could then be written in 2 lines of code. Run it, fix it
> if it does not work. Once you have success -
>
> Add (one at a time) various features:
> - roll dice to select winner
> - player names
> - repetition
>
> Continue to avoid writing functions. They are not necessary for such a
> simple program.

Not to butt in, but... As a newbie didn't you want to feel like a
sophisticated programmer and use functions to hold simple, and use
instances as your 'pride stance'.



>
> The final product will have less than 15 statements.
>
> also how do I display the winner under the displayInfo function?
>
> import random
>
> def main():
> ??? print
>
> ??? playerOne, playerTwo = inputNames(playerOne, PlayerTwo)
>
> ??? while endProgram == 'no':
>
> ??????? endProgram == no
> ??????? playerOne = 'NO NAME'
> ??????? playerTwo = 'NO NAME'
>
> ??????? winnerName = rollDice(p1number, p2number, playerOne, playerTwo,
> winnerName)
> ??????? winnerName = displayInfo
>
> ??????? endProgram = raw_input('Do you want to end program? (Enter yes or
> no): ')
>
> def inputNames(playerOne, PlayerTwo):
>
> ??? p1name = raw_input("Enter your name.")
> ??? p2name = raw_input("Enter your name.")
> ??? return playerOne, playerTwo
>
> def random(winnerName):
>
> ??? p1number = random.randint(1, 6)
> ??? p2number = random.randint(1, 6)
>
> ??? if p1number > p2number:
> ??????? playerOne = winnerName
> ??? elif p1number < p2number:
> ??????? playerTwo = winnerName
> ??? else p1number == p2number:
> ??????? playerOne, playerTwo = winnerName
>
> def displayInfo():
>
> ??? #how do I display winner?
>
> main()
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

From ehamiter at gmail.com  Sat Jul 31 20:45:21 2010
From: ehamiter at gmail.com (Eric Hamiter)
Date: Sat, 31 Jul 2010 13:45:21 -0500
Subject: [Tutor] Writing scripts and apps for Internet consumption
In-Reply-To: <AANLkTinR44Gpb5U694s1QvEhZV7aVX8qMe_2_yMNBatK@mail.gmail.com>
References: <AANLkTi=FkworTTqE_1wXOyT3PMbHDV8giSkjnCNa7UDo@mail.gmail.com> 
	<AANLkTinR44Gpb5U694s1QvEhZV7aVX8qMe_2_yMNBatK@mail.gmail.com>
Message-ID: <AANLkTi=T6+rPUHmBec4uB8voZxZZHLoP4CjwX7nKBLRk@mail.gmail.com>

>
> Get a linux hosting account, and a web address, most linux hosting
> comes with python, so practice in the 'cloud'.
>

I have that-- an account with Dreamhost. This hasn't solved my problems yet
though. Like I said, I can have it write a simple

Hello, World!

...but if I make it do anything more complex, I get a 404 error. To make my
question more simple-- how does one learn to create web apps with Python? It
seems to be that what it is advertised as, but not at all ready to go "out
of the box" for that type of thing. And that is fine, but I want to learn
how without having to learn a framework like Django-- yet. Or is this just
considered a kind of necessity?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100731/1c57a04c/attachment.html>

From smokefloat at gmail.com  Sat Jul 31 20:56:33 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 31 Jul 2010 14:56:33 -0400
Subject: [Tutor] Writing scripts and apps for Internet consumption
In-Reply-To: <AANLkTi=T6+rPUHmBec4uB8voZxZZHLoP4CjwX7nKBLRk@mail.gmail.com>
References: <AANLkTi=FkworTTqE_1wXOyT3PMbHDV8giSkjnCNa7UDo@mail.gmail.com>
	<AANLkTinR44Gpb5U694s1QvEhZV7aVX8qMe_2_yMNBatK@mail.gmail.com>
	<AANLkTi=T6+rPUHmBec4uB8voZxZZHLoP4CjwX7nKBLRk@mail.gmail.com>
Message-ID: <AANLkTimTU4oEnt8V6ngTDyUhN0+e=W3qNAkqg6uZ6oa+@mail.gmail.com>

On Sat, Jul 31, 2010 at 2:45 PM, Eric Hamiter <ehamiter at gmail.com> wrote:
>> Get a linux hosting account, and a web address, most linux hosting
>> comes with python, so practice in the 'cloud'.
>
> I have that-- an account with Dreamhost. This hasn't solved my problems yet
> though. Like I said, I can have it write a simple
>
> Hello, World!
>
> ...but if I make it do anything more complex, I get a 404 error. To make my
> question more simple-- how does one learn to create web apps with Python? It
> seems to be that what it is advertised as, but not at all ready to go "out
> of the box" for that type of thing. And that is fine, but I want to learn
> how without having to learn a framework like Django-- yet. Or is this just
> considered a kind of necessity?
>

What do your server logs show the 404 error to be?
Debug it like a script. For me, it's the part about use your own
computer as a host(I'm working on that) that gets me, but a hosting
account is already set up, as opposed to using your own local host
setup, this is provided. So it's just using the html with python just
like with php. I'm not an expert at this, but I do have a little
experience with lamp, so python should just be a replacement of p in
lamp for pythin instead of php

From michael at arpsorensen.dk  Sat Jul 31 20:49:28 2010
From: michael at arpsorensen.dk (=?UTF-8?Q?Michael_Bernhard_Arp_S=C3=B8rensen?=)
Date: Sat, 31 Jul 2010 20:49:28 +0200
Subject: [Tutor] Making a sound
Message-ID: <AANLkTi=1zTnbrC2M09ppQN8+gq8XtKpE3xy9grx=oWgz@mail.gmail.com>

Greetings, programs.

How do I create a sound from python? I'm thinking along the line of
generating a sinus wave where I can control the frequency and duration. I
want to produce a string of sounds based on a character string. Probably not
original. :-) I don't want to save a sound to a file and play it
afterwards. Preferably it should be something from PYPI. Any suggestions?

Thanks in advance.

Kind regards

Michael B. Arp S?rensen
Programmer / BOFH

"If you want to enter my network while I'm out, you can find my SSH-key
under my mouse mat" - Michael Bernhard Arp S?rensen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100731/46582e54/attachment-0001.html>

From smokefloat at gmail.com  Sat Jul 31 21:10:33 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 31 Jul 2010 15:10:33 -0400
Subject: [Tutor] Writing scripts and apps for Internet consumption
In-Reply-To: <AANLkTimTU4oEnt8V6ngTDyUhN0+e=W3qNAkqg6uZ6oa+@mail.gmail.com>
References: <AANLkTi=FkworTTqE_1wXOyT3PMbHDV8giSkjnCNa7UDo@mail.gmail.com>
	<AANLkTinR44Gpb5U694s1QvEhZV7aVX8qMe_2_yMNBatK@mail.gmail.com>
	<AANLkTi=T6+rPUHmBec4uB8voZxZZHLoP4CjwX7nKBLRk@mail.gmail.com>
	<AANLkTimTU4oEnt8V6ngTDyUhN0+e=W3qNAkqg6uZ6oa+@mail.gmail.com>
Message-ID: <AANLkTinyS_SnNsnkuMC1AO+a8NTBDr=h8BsVkAOGetE0@mail.gmail.com>

On Sat, Jul 31, 2010 at 2:56 PM, David Hutto <smokefloat at gmail.com> wrote:
> On Sat, Jul 31, 2010 at 2:45 PM, Eric Hamiter <ehamiter at gmail.com> wrote:
>>> Get a linux hosting account, and a web address, most linux hosting
>>> comes with python, so practice in the 'cloud'.
>>
>> I have that-- an account with Dreamhost. This hasn't solved my problems yet
>> though. Like I said, I can have it write a simple
>>
>> Hello, World!
>>
>> ...but if I make it do anything more complex, I get a 404 error. To make my
>> question more simple-- how does one learn to create web apps with Python? It
>> seems to be that what it is advertised as, but not at all ready to go "out
>> of the box" for that type of thing. And that is fine, but I want to learn
>> how without having to learn a framework like Django-- yet. Or is this just
>> considered a kind of necessity?
>>
>
> What do your server logs show the 404 error to be?
> Debug it like a script. For me, it's the part about use your own
> computer as a host(I'm working on that) that gets me, but a hosting
> account is already set up, as opposed to using your own local host
> setup, this is provided. So it's just using the html with python just
> like with php. I'm not an expert at this, but I do have a little
> experience with lamp, so python should just be a replacement of p in
> lamp for pythin instead of php
>

In other words, make it easy on yourself in the beginning, to avoid
frustration(and therefore a deterence of self toward your initial
language), and then learn the specifics in your downtime.

From rabidpoobear at gmail.com  Sat Jul 31 21:56:18 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sat, 31 Jul 2010 14:56:18 -0500
Subject: [Tutor] Making a sound
In-Reply-To: <AANLkTi=1zTnbrC2M09ppQN8+gq8XtKpE3xy9grx=oWgz@mail.gmail.com>
References: <AANLkTi=1zTnbrC2M09ppQN8+gq8XtKpE3xy9grx=oWgz@mail.gmail.com>
Message-ID: <24FCEBC9-F1AD-4206-AC93-A14C9DCBB169@gmail.com>

You can generate the sound data in a buffer either in native python or using numpy, then play it back by loading the buffer into a sound object with pygame. It depends how much control you want on the sounds. You might want to use csound or supercollider or something if you want to programmatically control a synth rather than directly creating the sound data.

Sent from my iPhone

On Jul 31, 2010, at 1:49 PM, Michael Bernhard Arp S?rensen <michael at arpsorensen.dk> wrote:

> Greetings, programs.
> 
> How do I create a sound from python? I'm thinking along the line of generating a sinus wave where I can control the frequency and duration. I want to produce a string of sounds based on a character string. Probably not original. :-) I don't want to save a sound to a file and play it afterwards. Preferably it should be something from PYPI. Any suggestions?
> 
> Thanks in advance.
> 
> Kind regards
> 
> Michael B. Arp S?rensen
> Programmer / BOFH
> 
> "If you want to enter my network while I'm out, you can find my SSH-key under my mouse mat" - Michael Bernhard Arp S?rensen
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From rschroev_nospam_ml at fastmail.fm  Sat Jul 31 22:06:01 2010
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Sat, 31 Jul 2010 22:06:01 +0200
Subject: [Tutor] Order Of Operations Question
In-Reply-To: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com>
References: <AANLkTimT+hRgQhz97-W+4oqJ=29g9Yp64yR7au7oxZcK@mail.gmail.com>
Message-ID: <i31vn9$gd7$1@dough.gmane.org>

Op 2010-07-28 11:41, David Hutto schreef:
> From a practice exercise in Building Skills In Python page 64 I'm
> working on How Much Does The Atmosphere Weigh? Part 1:
> To check it states that the answer should be app. 10**18kg However,
> and I've checked to make sure that the math I've layed out matches up
> with the texts, I get 5.07360705863e+20

Are looking for the _weight_ or the _mass_? They're the same in everyday
usage, but not in physical contexts. As far as I can see, you're
calculating the mass, not the weight. Does the book mention the units?
If it's kg, it's mass they mean, if it's N, it's weight.

In case they're really after the weight, your calculations get simpler:

import math
def atmosphereWeight():
    # Air pressure at sea level
    P0 = 1.01325e5
    # Approx. radius of earth
    R = 6.37e6
    # Approx. surface area of earth
    A = 4 * math.pi * R**2
    # Weight of atmosphere [units: N/m**2 * m**2 = N]
    Wa = P0 * A
    return Wa

Using that I get approx. 5.17e19, which is about 50 times larger than
the 1e18 value in the book. I guess my guess was incorrect, and they're
really after the mass (which, according to my calculations, is 5.17e19 /
9.81 = 5.27e18; 'only' about 5 times larger than the value in the book).

-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
  -- Isaac Asimov

Roel Schroeven


From bgailer at gmail.com  Sat Jul 31 23:48:01 2010
From: bgailer at gmail.com (bob gailer)
Date: Sat, 31 Jul 2010 17:48:01 -0400
Subject: [Tutor] Writing scripts and apps for Internet consumption
In-Reply-To: <AANLkTi=T6+rPUHmBec4uB8voZxZZHLoP4CjwX7nKBLRk@mail.gmail.com>
References: <AANLkTi=FkworTTqE_1wXOyT3PMbHDV8giSkjnCNa7UDo@mail.gmail.com>
	<AANLkTinR44Gpb5U694s1QvEhZV7aVX8qMe_2_yMNBatK@mail.gmail.com>
	<AANLkTi=T6+rPUHmBec4uB8voZxZZHLoP4CjwX7nKBLRk@mail.gmail.com>
Message-ID: <4C549A11.40807@gmail.com>

On 7/31/2010 2:45 PM, Eric Hamiter wrote:
>
>     Get a linux hosting account, and a web address, most linux hosting
>     comes with python, so practice in the 'cloud'.
>
>
> I have that-- an account with Dreamhost. This hasn't solved my 
> problems yet though. Like I said, I can have it write a simple
>
> Hello, World!

Please post that code, and the URL you use to invoke it.
>
> ...but if I make it do anything more complex, I get a 404 error. 

Please post that code, and the URL you use to invoke it.

Do you import cgi?

There is a companion module (cgitb) that captures exceptions and returns 
the traceback to the web browser.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100731/2e7f5bed/attachment.html>