From mlybrand at gmail.com  Sun Jan  1 00:22:39 2012
From: mlybrand at gmail.com (Mark Lybrand)
Date: Sat, 31 Dec 2011 15:22:39 -0800
Subject: [Tutor] ez_setup.py for Python3 64-bit on Vista
Message-ID: <CALsUBtzOkrrJgB_QgCp50p9BKJ0SxMZYwzZhP5is4wjL2mJXNQ@mail.gmail.com>

I have found this script:

http://peak.telecommunity.com/dist/ez_setup.py<http://pypi.python.org/pypi/setuptools>

But I can see that this is Python 2.x  Is there a Python 3 version, or
should I be doing something else to install an .egg on my system?

Thanks in advance.

-- 
Mark :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111231/a7fdab35/attachment.html>

From wprins at gmail.com  Sun Jan  1 03:50:35 2012
From: wprins at gmail.com (Walter Prins)
Date: Sun, 1 Jan 2012 02:50:35 +0000
Subject: [Tutor] ez_setup.py for Python3 64-bit on Vista
In-Reply-To: <CALsUBtzOkrrJgB_QgCp50p9BKJ0SxMZYwzZhP5is4wjL2mJXNQ@mail.gmail.com>
References: <CALsUBtzOkrrJgB_QgCp50p9BKJ0SxMZYwzZhP5is4wjL2mJXNQ@mail.gmail.com>
Message-ID: <CANLXbfBGhr+mBJhHeeQ16=W9cSVMD-n16kpE2rWa_BWAK_XrMA@mail.gmail.com>

Hi,

On 31 December 2011 23:22, Mark Lybrand <mlybrand at gmail.com> wrote:
> I have found this script:
>
> http://peak.telecommunity.com/dist/ez_setup.py
>
> But I can see that this is Python 2.x? Is there a Python 3 version, or
> should I be doing something else to install an .egg on my system?

There isn't an official version of setuptools for Python 3.x.  Use
"distribute" instead, which is a fork of setuptools and is available
for Python 3.x:
http://pypi.python.org/pypi/distribute#disclaimers

... and/or use "Pip":
http://www.pip-installer.org/en/latest/index.html

To install "distribute", download the "distribute_setup.py" file from
the above pages, then open a command prompt and run the downloaded
Python script with your Python 3.2 interpreter.  The command wil be
something like:
C:\Python32\Python.exe C:\Users\Mark\Downloads\distribute_setup.py

(here I'm assuming your Python interpreter path is C:\Python32 and
that you've downloaded the distribute_setup.py file to
C:\Users\Mark\Downloads.  You'll have to adjust this accordingly.
Once this is done, you'll have a new command/script in
C:\Python32\Scripts.  So, if you do:
cd c:\Python32\Scripts
dir

... you'll see the newly installed script.  Additionally you can then
trivially also install "pip", by executing:

easy_install pip

from the command prompt.

HTH,

Walter

From mlybrand at gmail.com  Sun Jan  1 04:13:21 2012
From: mlybrand at gmail.com (Mark Lybrand)
Date: Sat, 31 Dec 2011 19:13:21 -0800
Subject: [Tutor] ez_setup.py for Python3 64-bit on Vista
In-Reply-To: <CANLXbfBGhr+mBJhHeeQ16=W9cSVMD-n16kpE2rWa_BWAK_XrMA@mail.gmail.com>
References: <CALsUBtzOkrrJgB_QgCp50p9BKJ0SxMZYwzZhP5is4wjL2mJXNQ@mail.gmail.com>
	<CANLXbfBGhr+mBJhHeeQ16=W9cSVMD-n16kpE2rWa_BWAK_XrMA@mail.gmail.com>
Message-ID: <CALsUBtzFd7_3A4ZGEh4j1+-tdET5CDV0qReQzhJMXBKz2MAReg@mail.gmail.com>

... you'll see the newly installed script.  Additionally you can then

> trivially also install "pip", by executing:
>
> easy_install pip
>
>
Does this triviality depend on where the pip files are that I wish to "easy
install"?  I would assume that the answer is "yes". In which case, if those
pip files are in my Download folder, will the easy install put them in the
right place or reference them from the Download folder?

Mark
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111231/60926eb4/attachment.html>

From mlybrand at gmail.com  Sun Jan  1 04:21:52 2012
From: mlybrand at gmail.com (Mark Lybrand)
Date: Sat, 31 Dec 2011 19:21:52 -0800
Subject: [Tutor] ez_setup.py for Python3 64-bit on Vista
In-Reply-To: <CANLXbfBGhr+mBJhHeeQ16=W9cSVMD-n16kpE2rWa_BWAK_XrMA@mail.gmail.com>
References: <CALsUBtzOkrrJgB_QgCp50p9BKJ0SxMZYwzZhP5is4wjL2mJXNQ@mail.gmail.com>
	<CANLXbfBGhr+mBJhHeeQ16=W9cSVMD-n16kpE2rWa_BWAK_XrMA@mail.gmail.com>
Message-ID: <CALsUBtx8G-q15nOZGOGhYHVxQw50nYVvCU+8mH4MvKups=Wy8g@mail.gmail.com>

I think I got it actually.  Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111231/c5b30051/attachment.html>

From wprins at gmail.com  Sun Jan  1 06:02:26 2012
From: wprins at gmail.com (Walter Prins)
Date: Sun, 1 Jan 2012 05:02:26 +0000
Subject: [Tutor] ez_setup.py for Python3 64-bit on Vista
In-Reply-To: <CALsUBtzFd7_3A4ZGEh4j1+-tdET5CDV0qReQzhJMXBKz2MAReg@mail.gmail.com>
References: <CALsUBtzOkrrJgB_QgCp50p9BKJ0SxMZYwzZhP5is4wjL2mJXNQ@mail.gmail.com>
	<CANLXbfBGhr+mBJhHeeQ16=W9cSVMD-n16kpE2rWa_BWAK_XrMA@mail.gmail.com>
	<CALsUBtzFd7_3A4ZGEh4j1+-tdET5CDV0qReQzhJMXBKz2MAReg@mail.gmail.com>
Message-ID: <CANLXbfCn-cDQA73MVLmrMi4qcMHVU55bP3Vq9bGsFAyhEzQS2A@mail.gmail.com>

Hi Mark

On 1 January 2012 03:13, Mark Lybrand <mlybrand at gmail.com> wrote:
> ... you'll see the newly installed script. ?Additionally you can then
>>
>> trivially also install "pip", by executing:
>>
>> easy_install pip
>>
>
> Does this triviality depend on where the pip files are that I wish to "easy
> install"?? I would assume that the answer is "yes". In which case, if those
> pip files are in my Download folder, will the easy install put them in the
> right place or reference them from the Download folder?

No -- easy_install does everything for you.  The command:

easy_install pip

both downloads and installs the package named "pip" for you.  (It so
happens that "pip" is another package management tool, but the point
is that you can install any Python package this way, simply by
specifying the package name that you want to install.)

That's part of the beauty of the inbuilt package management support in
Python.  You merely have to specify the package you'd like to install,
and distribute (via the command "easy_install") or pip (via the
command "pip") will (in general) go and locate the correct version of
a python package and install it for you.  Packages with C modules are
however much more problematic since you need a C compiler to install
them, and so in general it's far easier for such packages to find a
pre-packages Windows installer package witht he C modules already
compiled for you.  (If you're sufficiently familiar with C compilers
on Windows and projects like MinGW or tools like Visual Studio on
Windows, as well as how Windows works generally, then it's possible to
set your system up to have pip or distribute install your C based
Python modules as well.)

Hope that clarifies things,

Walter

From sierra_mtnview at sbcglobal.net  Sun Jan  1 20:29:52 2012
From: sierra_mtnview at sbcglobal.net (Wayne Watson)
Date: Sun, 01 Jan 2012 11:29:52 -0800
Subject: [Tutor] Which libraries for Python 2.5.2 [SOLVED]
In-Reply-To: <4EF8D163.1020007@sbcglobal.net>
References: <4EF60DF5.7070100@sbcglobal.net>
	<CAJmBOfmMVZKjpUz4KfGyxxyZkAY4K5WTCrHtvoXdsg1qTVEBbA@mail.gmail.com>
	<4EF8CEB9.5090505@sbcglobal.net> <4EF8D163.1020007@sbcglobal.net>
Message-ID: <4F00B430.7090607@sbcglobal.net>

This problem was solved when my wife noticed that there was a second 
install disk for the 5 year old XP zx6000 PC she had given me, which I 
will now give to a friend.

The problem originally was a missing dll that Python wanted.  All is 
well now.

-- 
            Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

              (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
               Obz Site:  39? 15' 7" N, 121? 2' 32" W, 2700 feet

                      CE 1955 October 20 07:53:32.6 UT
                     -- "The Date" The mystery unfolds.

                     Web Page:<www.speckledwithstars.net/>



From stayvoid at gmail.com  Sun Jan  1 20:40:13 2012
From: stayvoid at gmail.com (Stayvoid)
Date: Sun, 1 Jan 2012 22:40:13 +0300
Subject: [Tutor] Class vs. instance
Message-ID: <CAK5fS_FDj8no7+nEUma0EwAFOgXd=548p17j4E2zqiD2oKZ+Yg@mail.gmail.com>

Hi there!

>>> class Sample:
>>>     def method(self): pass

>>> Sample().method()

What's the difference between class __main__.Sample and
__main__.Sample instance?
Why should I write "Sample().method" instead of "Sample.method"?


Cheers!

From hugo.yoshi at gmail.com  Sun Jan  1 23:03:46 2012
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sun, 1 Jan 2012 23:03:46 +0100
Subject: [Tutor] Class vs. instance
In-Reply-To: <CAK5fS_FDj8no7+nEUma0EwAFOgXd=548p17j4E2zqiD2oKZ+Yg@mail.gmail.com>
References: <CAK5fS_FDj8no7+nEUma0EwAFOgXd=548p17j4E2zqiD2oKZ+Yg@mail.gmail.com>
Message-ID: <CAJmBOfkGSLbMBrdd3=cOjMoPrWDVZMZ_u3SNSGZqiWgXvV1LSw@mail.gmail.com>

On Sun, Jan 1, 2012 at 8:40 PM, Stayvoid <stayvoid at gmail.com> wrote:
> Hi there!
>
>>>> class Sample:
>>>> ? ? def method(self): pass
>
>>>> Sample().method()
>
> What's the difference between class __main__.Sample and
> __main__.Sample instance?
> Why should I write "Sample().method" instead of "Sample.method"?
>

The difference can be illustrated as such:

>>> Sample().method
<bound method Sample.method of <__main__.Sample instance at 0x1004d1638>>
>>> Sample().method()
>>> Sample.method
<unbound method Sample.method>
>>> Sample.method()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method method() must be called with Sample instance
as first argument (got nothing instead)
>>>

That is, the difference between the methods is that the accessed
through the instance is also attached to that instance. It will
automagically get Sample() passed to it as its first argument (that
would be self). The one attached to the class is unbound, which means
that you can do this:

>>> Sample.method(Sample())
>>>

With any Sample instance, of course. This exposes a bit of syntax
sugar in python and how classes are really implemented, essentially
the fact that, if "a" is a sample instance, a.method(arg1, arg2, arg3)
is actually just Sample.method(a, arg1, arg2, arg3)

HTH,
Hugo

From stayvoid at gmail.com  Sun Jan  1 23:26:11 2012
From: stayvoid at gmail.com (Stayvoid)
Date: Mon, 2 Jan 2012 01:26:11 +0300
Subject: [Tutor] Class vs. instance
In-Reply-To: <CAJmBOfkGSLbMBrdd3=cOjMoPrWDVZMZ_u3SNSGZqiWgXvV1LSw@mail.gmail.com>
References: <CAK5fS_FDj8no7+nEUma0EwAFOgXd=548p17j4E2zqiD2oKZ+Yg@mail.gmail.com>
	<CAJmBOfkGSLbMBrdd3=cOjMoPrWDVZMZ_u3SNSGZqiWgXvV1LSw@mail.gmail.com>
Message-ID: <CAK5fS_Gpo8unEjq3mz7dD2WuCSMO-Tei-6Vh_kHOOafT4cZXNw@mail.gmail.com>

Thanks.

I totally get it now.

From brianjamesarb at gmail.com  Mon Jan  2 03:48:58 2012
From: brianjamesarb at gmail.com (brian arb)
Date: Sun, 1 Jan 2012 21:48:58 -0500
Subject: [Tutor] while loop ends prematurly
Message-ID: <CABYizFLCpYKD2J+0nDG24QK6LM2T=sP-E2qkOJ_7HWvN93sQbw@mail.gmail.com>

Hello,
Can some please explain this to me?
My while loop should continue while "owed" is greater than or equal to "d"

first time the function is called
the loop exits as expected
False: 0.000000 >= 0.010000
the next time it does not
False: 0.010000 >= 0.010000

Below is the snippet of code, and the out put.

Thanks!

def make_change(arg):
  denom = [100.0, 50.0, 20.0, 10.0, 5.0, 1.0, 0.25, 0.10, 0.05, 0.01]
  owed = float(arg)
  payed = []
  for d in denom:
    while owed >= d:
      owed -= d
      b = owed >= d
      print '%s: %f >= %f' % (b, owed, d)
      payed.append(d)
  print sum(payed), payed
  return sum(payed)

if __name__ == '__main__':
  values = [21.48, 487.69] #, 974.41, 920.87, 377.93, 885.12, 263.47,
630.91, 433.23, 800.58]
  for i in values:
    make_change(i))


False: 1.480000 >= 20.000000
False: 0.480000 >= 1.000000
False: 0.230000 >= 0.250000
True: 0.130000 >= 0.100000
False: 0.030000 >= 0.100000
True: 0.020000 >= 0.010000
True: 0.010000 >= 0.010000
False: 0.000000 >= 0.010000
21.48 [20.0, 1.0, 0.25, 0.1, 0.1, 0.01, 0.01, 0.01]
True: 387.690000 >= 100.000000
True: 287.690000 >= 100.000000
True: 187.690000 >= 100.000000
False: 87.690000 >= 100.000000
False: 37.690000 >= 50.000000
False: 17.690000 >= 20.000000
False: 7.690000 >= 10.000000
False: 2.690000 >= 5.000000
True: 1.690000 >= 1.000000
False: 0.690000 >= 1.000000
True: 0.440000 >= 0.250000
False: 0.190000 >= 0.250000
False: 0.090000 >= 0.100000
False: 0.040000 >= 0.050000
True: 0.030000 >= 0.010000
True: 0.020000 >= 0.010000
False: 0.010000 >= 0.010000
487.68 [100.0, 100.0, 100.0, 100.0, 50.0, 20.0, 10.0, 5.0, 1.0, 1.0, 0.25,
0.25, 0.1, 0.05, 0.01, 0.01, 0.01]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120101/9600a323/attachment.html>

From d at davea.name  Mon Jan  2 04:25:57 2012
From: d at davea.name (Dave Angel)
Date: Sun, 01 Jan 2012 22:25:57 -0500
Subject: [Tutor] while loop ends prematurly
In-Reply-To: <CABYizFLCpYKD2J+0nDG24QK6LM2T=sP-E2qkOJ_7HWvN93sQbw@mail.gmail.com>
References: <CABYizFLCpYKD2J+0nDG24QK6LM2T=sP-E2qkOJ_7HWvN93sQbw@mail.gmail.com>
Message-ID: <4F0123C5.6000005@davea.name>

On 01/01/2012 09:48 PM, brian arb wrote:
> Hello,
> Can some please explain this to me?
> My while loop should continue while "owed" is greater than or equal to "d"
>
> first time the function is called
> the loop exits as expected
> False: 0.000000>= 0.010000
> the next time it does not
> False: 0.010000>= 0.010000
>
> Below is the snippet of code, and the out put.
>
> Thanks!
>
> def make_change(arg):
>    denom = [100.0, 50.0, 20.0, 10.0, 5.0, 1.0, 0.25, 0.10, 0.05, 0.01]
>    owed = float(arg)
>    payed = []
>    for d in denom:
>      while owed>= d:
>        owed -= d
>        b = owed>= d
>        print '%s: %f>= %f' % (b, owed, d)
>        payed.append(d)
>    print sum(payed), payed
>    return sum(payed)
>
> if __name__ == '__main__':
>    values = [21.48, 487.69] #, 974.41, 920.87, 377.93, 885.12, 263.47,
> 630.91, 433.23, 800.58]
>    for i in values:
>      make_change(i))
>
>
> False: 1.480000>= 20.000000
> False: 0.480000>= 1.000000
> False: 0.230000>= 0.250000
> True: 0.130000>= 0.100000
> False: 0.030000>= 0.100000
> True: 0.020000>= 0.010000
> True: 0.010000>= 0.010000
> False: 0.000000>= 0.010000
> 21.48 [20.0, 1.0, 0.25, 0.1, 0.1, 0.01, 0.01, 0.01]
> True: 387.690000>= 100.000000
> True: 287.690000>= 100.000000
> True: 187.690000>= 100.000000
> False: 87.690000>= 100.000000
> False: 37.690000>= 50.000000
> False: 17.690000>= 20.000000
> False: 7.690000>= 10.000000
> False: 2.690000>= 5.000000
> True: 1.690000>= 1.000000
> False: 0.690000>= 1.000000
> True: 0.440000>= 0.250000
> False: 0.190000>= 0.250000
> False: 0.090000>= 0.100000
> False: 0.040000>= 0.050000
> True: 0.030000>= 0.010000
> True: 0.020000>= 0.010000
> False: 0.010000>= 0.010000
> 487.68 [100.0, 100.0, 100.0, 100.0, 50.0, 20.0, 10.0, 5.0, 1.0, 1.0, 0.25,
> 0.25, 0.1, 0.05, 0.01, 0.01, 0.01]
>
You're using float values and pretending that they can accurately 
represent dollars and cents. 0.19 (for example) cannot be exactly 
represented in a float, and when you start adding up multiple of these, 
sooner or later the error will become visible.  This is a problem with 
binary floating point, and I first encountered it in 1967, when the 
textbook for Fortran made an important point about never comparing 
floating point values for equals, as small invisible errors are bound to 
bite you.

Easiest answer is to use integers.  Scale everything up by a factor of 
100, and you won't need floats at all.  Just convert when printing (and 
even then you may get into trouble).

Another answer is to use Decimal class, which CAN represent decimal 
values exactly.

BTW, if this is supposed to represent US legal tender, you left out the 
fifty-cent piece as well as the two dollar bill.

-- 

DaveA


From hugo.yoshi at gmail.com  Mon Jan  2 05:02:54 2012
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Mon, 2 Jan 2012 05:02:54 +0100
Subject: [Tutor] while loop ends prematurly
In-Reply-To: <CABYizFLCpYKD2J+0nDG24QK6LM2T=sP-E2qkOJ_7HWvN93sQbw@mail.gmail.com>
References: <CABYizFLCpYKD2J+0nDG24QK6LM2T=sP-E2qkOJ_7HWvN93sQbw@mail.gmail.com>
Message-ID: <CAJmBOfkjePXYoaiMkZSw7XLj_ag7tPz2igxPUJY=78xGmBtysg@mail.gmail.com>

On Mon, Jan 2, 2012 at 3:48 AM, brian arb <brianjamesarb at gmail.com> wrote:
> Hello,
> Can some please explain this to me?
> My while loop should continue while "owed" is greater than or equal to "d"
>
> first time the function is called
> the loop exits as expected
> False: 0.000000 >= 0.010000
> the next time it does not
> False: 0.010000 >= 0.010000
>
> Below is the snippet of code, and the out put.
>
> Thanks!
>
> def make_change(arg):
> ? denom = [100.0, 50.0, 20.0, 10.0, 5.0, 1.0, 0.25, 0.10, 0.05, 0.01]
> ? owed = float(arg)
> ? payed = []
> ? for d in denom:
> ? ? while owed >= d:
> ? ? ? owed -= d
> ? ? ? b = owed >= d
> ? ? ? print '%s: %f >= %f' % (b, owed, d)
> ? ? ? payed.append(d)
> ? print sum(payed), payed
> ? return sum(payed)
>
> if __name__ == '__main__':
> ? values = [21.48, 487.69] #, 974.41, 920.87, 377.93, 885.12, 263.47,
> 630.91, 433.23, 800.58]
> ? for i in values:
> ? ? make_change(i))
>
>
> False: 1.480000 >= 20.000000
> False: 0.480000 >= 1.000000
> False: 0.230000 >= 0.250000
> True: 0.130000 >= 0.100000
> False: 0.030000 >= 0.100000
> True: 0.020000 >= 0.010000
> True: 0.010000 >= 0.010000
> False: 0.000000 >= 0.010000
> 21.48 [20.0, 1.0, 0.25, 0.1, 0.1, 0.01, 0.01, 0.01]
> True: 387.690000 >= 100.000000
> True: 287.690000 >= 100.000000
> True: 187.690000 >= 100.000000
> False: 87.690000 >= 100.000000
> False: 37.690000 >= 50.000000
> False: 17.690000 >= 20.000000
> False: 7.690000 >= 10.000000
> False: 2.690000 >= 5.000000
> True: 1.690000 >= 1.000000
> False: 0.690000 >= 1.000000
> True: 0.440000 >= 0.250000
> False: 0.190000 >= 0.250000
> False: 0.090000 >= 0.100000
> False: 0.040000 >= 0.050000
> True: 0.030000 >= 0.010000
> True: 0.020000 >= 0.010000
> False: 0.010000 >= 0.010000
> 487.68 [100.0, 100.0, 100.0, 100.0, 50.0, 20.0, 10.0, 5.0, 1.0, 1.0, 0.25,
> 0.25, 0.1, 0.05, 0.01, 0.01, 0.01]
>

What happened is that you ran into the weirdness that we call the IEEE
754-2008 standard, otherwise known as floating point numbers. in quite
simple terms, the way the computer represents floating point numbers
means that inaccuracies sneak in when performing math on them, and
some numbers can't even be represented correctly, like 0.1. You can
notice this in some of the simplest calculations:

>>> 0.1
0.1
>>> # seems normal? Well, python is actually tricking you. Let's force it to show us this number with some more accuracy:
>>> "%.32f" % 0.1 # force it to show 32 digits after the period
'0.10000000000000000555111512312578'
>>> # whoops! that's not quite 0.1 at all! let's try some more:
>>> 9 * 0.1
0.9
>>> 0.9
0.9
>>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1
0.8999999999999999
>>> "%.32f" % 0.9
'0.90000000000000002220446049250313'
>>> # what?! those aren't even the same numbers!!
>>> 0.1 + 0.2
0.30000000000000004
>>> # what the hell?

Usually this doesn't really matter, because we don't really care about
what happens after you get way far into the decimal spaces. But when
you compare for equality, which is what you're doing here, this stuff
can bite you in the ass real ugly. If you replace the %f with %.32f in
that debugging statement, you'll see why the loop bails:

False: 0.0099999999999977 >= 0.0100000000000000

That kinda sucks, doesn't it? floating point errors are hard to find,
especially since python hides them from you sometimes. But there is a
simple solution! Multiply all numbers by 100 inside that function and
then simply work with integers, where you do get perfect accuracy.

HTH,
Hugo

P.S.: this problem is not in inherent to python but to the IEEE
standard. The sacrifice in accuracy was made deliberately to keep
floating point numbers fast, so it's by design and not something that
should be "fixed." Pretty much all languages that use floats or
doubles have the same thing. If you really want decimal numbers, there
is a Decimal class in Python that implements 100% accurate decimal
numbers at the cost of performance. Look it up.

P.P.S.: for more information you should read these. The first link is
a simple explanation. The second is more complicated, but obligatory
reading material for every programmer worth his salts:
the floating point guide: http://floating-point-gui.de/
what every computer scientist should know about floating-point
arithmetic: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

From steve at pearwood.info  Mon Jan  2 07:28:39 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 02 Jan 2012 17:28:39 +1100
Subject: [Tutor] while loop ends prematurly
In-Reply-To: <4F0123C5.6000005@davea.name>
References: <CABYizFLCpYKD2J+0nDG24QK6LM2T=sP-E2qkOJ_7HWvN93sQbw@mail.gmail.com>
	<4F0123C5.6000005@davea.name>
Message-ID: <4F014E97.5080901@pearwood.info>

Dave Angel wrote:

> Easiest answer is to use integers.  Scale everything up by a factor of 
> 100, and you won't need floats at all.  Just convert when printing (and 
> even then you may get into trouble).
> 
> Another answer is to use Decimal class, which CAN represent decimal 
> values exactly.

That only applies to decimal values which can be represented using a fixed 
number of decimal places. So 1/5 is fine, and is 0.2 exactly, but 1/3 is not, 
since it would require an infinite number of decimal places.

> BTW, if this is supposed to represent US legal tender, you left out the 
> fifty-cent piece as well as the two dollar bill.

http://kowb1290.com/our-two-cents-on-the-two-dollar-bill/



-- 
Steven


From wprins at gmail.com  Mon Jan  2 11:51:01 2012
From: wprins at gmail.com (Walter Prins)
Date: Mon, 2 Jan 2012 10:51:01 +0000
Subject: [Tutor] while loop ends prematurly
In-Reply-To: <4F014E97.5080901@pearwood.info>
References: <CABYizFLCpYKD2J+0nDG24QK6LM2T=sP-E2qkOJ_7HWvN93sQbw@mail.gmail.com>
	<4F0123C5.6000005@davea.name> <4F014E97.5080901@pearwood.info>
Message-ID: <CANLXbfAoc0KujA6n3gJCTO8sRN67oz0FkAccJFtYT1qd+dwKjQ@mail.gmail.com>

Hi Steven,

On 2 January 2012 06:28, Steven D'Aprano <steve at pearwood.info> wrote:
> That only applies to decimal values which can be represented using a fixed
> number of decimal places. So 1/5 is fine, and is 0.2 exactly, but 1/3 is
> not, since it would require an infinite number of decimal places.

Just a small nit pick with the above:  1/3 is however not a decimal
number.   The word decimal means "tenth part", decimal numbers are
generally defined/understood as numbers that are expressible as
decimal fractions, meaning numbers where the denominator is a power of
10 or is an exact "tenth part".  Understood as such, decimal numbers
are therefore obviously accurately representable by the Decimal class
which is the whole point of calling the class "Decimal".

To backtrack slightly, numbers like 1/3, 1/5 etc are in general called
common or vulgar fractions, the only requirement being that they have
an integer numerator and an integer non-zero denominator.  The class
of numbers representible like this is called rational numbers and the
test for whether a number can be called rational is whether it can be
written as such.

The set of numbers we refer to as decimal numbers then, are a subset
of rational numbers, the test for whether they can be called decimal
being whether they can be written as a rational number with the
additional requirement that the denominator be a power of ten.
Addtionally, any rational number with a denominator of which the prime
factors are 2 and 5 may therefore be rewritten as a decimal number,
thus we know that 2/5 can also be accurately represented by a decimal
number (since the prime factors of 5 is 5), as can 1/50 (since the
prime factors of 50 are 2,5,5), but 1/3 can not, since 3 has only 3 as
its prime factor (and not 2 or 5), and neither 1/24 (since the prime
factors are 2,2,2,3).  So an additional test for whether a given
rational number can be accurately rewritten as a decimal (tenth part)
number, is to inspect the prime factors of the denominator.  If this
consists solely of 2's and 5's it can be expressed as a decimal, if
any other factors are present then it cannot be accurately expressed
as a decimal.

A happy and prosperous 2012 to all,

Walter

From d at davea.name  Mon Jan  2 15:01:02 2012
From: d at davea.name (Dave Angel)
Date: Mon, 02 Jan 2012 09:01:02 -0500
Subject: [Tutor] while loop ends prematurly
In-Reply-To: <CABFCkKRe7N9BL5BWZT=CqgMPz1Vq3k-7pP_fFKeFcfi0O770Bw@mail.gmail.com>
References: <CABYizFLCpYKD2J+0nDG24QK6LM2T=sP-E2qkOJ_7HWvN93sQbw@mail.gmail.com>	<4F0123C5.6000005@davea.name>
	<CABFCkKRe7N9BL5BWZT=CqgMPz1Vq3k-7pP_fFKeFcfi0O770Bw@mail.gmail.com>
Message-ID: <4F01B89E.2090606@davea.name>

(You accidentally forgot to include the list when you replied.  The 
easiest way (for most people) to avoid that is to use Reply-all)

On 01/02/2012 01:00 AM, Sarma Tangirala wrote:
> On 2 Jan 2012 08:56, "Dave Angel"<d at davea.name>  wrote:
>>
>> Easiest answer is to use integers.  Scale everything up by a factor of
> 100, and you won't need floats at all.  Just convert when printing (and
> even then you may get into trouble).
>
> Just to add a bit here. I've seen a couple of people do it this way -
> subtract the two numbers and check if the result is above a particular
> threshold value, and if so they are not equal.
>
That was also in that Fortran reference from '67.  The trick on that is 
to subtract, and compare the absolute value to an epsilon value.

if abs(a-b)< threshold:
     equals-logic goes here
else:
     unequals-logic goes here

It can get tricky to pick a good threshold. In this case, a thousandth 
of a penny is clearly enough.  But for many programs the threshold also 
has to be calculated.

In APL, this comparison logic is automated, via a concept called fuzz. 
You typically specify the fuzz value once, and the threshold is 
automatically calculated by something like multiplying fuzz by the 
larger (in absolute value) of the two numbers being compared.

These approaches are also tricky, and when they fail, debugging them can 
be very difficult.

>>
>> Another answer is to use Decimal class, which CAN represent decimal
> values exactly.
>>
>>

When I implemented the microcode math package for a processor (which 
predated microprocessors like the 8080 and 8086), it was all decimal. 
We had decimal logic in the hardware for adding two-digit integers, 
everything more complicated was a loop in the microcode.  With that 
system, if you printed out a value, you saw an exact equivalent of what 
was stored internally.

-- 

DaveA

From wprins at gmail.com  Mon Jan  2 15:02:58 2012
From: wprins at gmail.com (Walter Prins)
Date: Mon, 2 Jan 2012 14:02:58 +0000
Subject: [Tutor] while loop ends prematurly
In-Reply-To: <4F014E97.5080901@pearwood.info>
References: <CABYizFLCpYKD2J+0nDG24QK6LM2T=sP-E2qkOJ_7HWvN93sQbw@mail.gmail.com>
	<4F0123C5.6000005@davea.name> <4F014E97.5080901@pearwood.info>
Message-ID: <CANLXbfDDVM30twwXmk+e1MRTg--ycFUhP221-zgzHjiuS+CBHw@mail.gmail.com>

Hi again,

On 2 January 2012 06:28, Steven D'Aprano <steve at pearwood.info> wrote:
>> Another answer is to use Decimal class, which CAN represent decimal values
>> exactly.
>
>
> That only applies to decimal values which can be represented using a fixed
> number of decimal places. So 1/5 is fine, and is 0.2 exactly, but 1/3 is
> not, since it would require an infinite number of decimal places.

It's occurred to me that I should've probably used the term "exact
decimal" in my comment, so please read it as such.  (The general class
of decimals include 3 types of decimals: exact, recurring and
non-recurring.  Generally when people use the word decimal they tend
to mean "exact decimals".  Apologies for not being clearer.)

Walter

From rhettnaxel at gmail.com  Mon Jan  2 17:30:27 2012
From: rhettnaxel at gmail.com (Alexander)
Date: Mon, 2 Jan 2012 11:30:27 -0500
Subject: [Tutor] Touch Screen
Message-ID: <CANS6qmD4BeeoxKsitiywSKR37yFC9QEFTQ5=fpvkgYJX7nA9MQ@mail.gmail.com>

Hi. Just curious if there are any ideas on how to use python with a touch
screen. That is a stand alone touchscreen, not something running on a
desktop or personal computer; consider a touch screen dedicated to one
purpose, like a cash register, running python.
Thanks,
Alexander
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120102/d93121f6/attachment.html>

From alan.gauld at btinternet.com  Mon Jan  2 19:07:50 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 02 Jan 2012 18:07:50 +0000
Subject: [Tutor] Touch Screen
In-Reply-To: <CANS6qmD4BeeoxKsitiywSKR37yFC9QEFTQ5=fpvkgYJX7nA9MQ@mail.gmail.com>
References: <CANS6qmD4BeeoxKsitiywSKR37yFC9QEFTQ5=fpvkgYJX7nA9MQ@mail.gmail.com>
Message-ID: <jdsrpn$ok$1@dough.gmane.org>

On 02/01/12 16:30, Alexander wrote:
> Hi. Just curious if there are any ideas on how to use python with a
> touch screen. That is a stand alone touchscreen, not something running
> on a desktop or personal computer;

A touchscreen has no intrrinsic iontelligence so it must have sopme kind 
of computer behind it. That computer will need to be running an 
Operating System before you can use Python. Interpreting the touchscreen 
will be a function of the Operating System and you then only need to 
figure out how the Operating System represents the touch screen to you 
as an application programmer.

But until you know what OS is being used you can't even be sure that you 
can run Python. (The good news is that some kind of Python is available 
on most OS!)

> one purpose, like a cash register, running python.

Cash Register is just another application running on top of an OS (at 
least in all the cases I've seen, (usually Windows), and Python would be 
another application running alongside the CashRegister app.

There may be a few cash registers rthat implemenmt their own embedded 
hardware monitor but the cost of developing such a thing is so high 
(especially compared to Linux!) that most devices like that use a 
regular OS and just disguise it with a single app as the "desktop".

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


From wprins at gmail.com  Mon Jan  2 19:43:15 2012
From: wprins at gmail.com (Walter Prins)
Date: Mon, 2 Jan 2012 18:43:15 +0000
Subject: [Tutor] Touch Screen
In-Reply-To: <jdsrpn$ok$1@dough.gmane.org>
References: <CANS6qmD4BeeoxKsitiywSKR37yFC9QEFTQ5=fpvkgYJX7nA9MQ@mail.gmail.com>
	<jdsrpn$ok$1@dough.gmane.org>
Message-ID: <CANLXbfDnwbcXQRLaJX_EE=CtnQsg+DLKCW3dkOdF8+Wv3baCcA@mail.gmail.com>

Hi,

On 2 January 2012 18:07, Alan Gauld <alan.gauld at btinternet.com> wrote:
> There may be a few cash registers rthat implemenmt their own embedded
> hardware monitor but the cost of developing such a thing is so high
> (especially compared to Linux!) that most devices like that use a regular OS
> and just disguise it with a single app as the "desktop".

Just to add to what Alan's said, and with apologies if appropriate as
its arguably only tangentially relevant to your question, but you may
be interested to keep an eye on the "Raspberry Pi", a 25$ computer
(yes, $25) that's due for release in Jan 2012.  It will primarily use
Python as programming language although others will be supported. (Not
entirely suprising given that the OS is GNU/Linux.)  For more see
here:

http://en.wikipedia.org/wiki/Raspberry_Pi
http://articles.businessinsider.com/2011-12-28/tech/30564049_1_computer-broadcom-foundation
http://www.raspberrypi.org/faqs

It seems that for anyone who wants to build his own device on the
cheap from commodity hardware, something like this with a suitably
configured Linux distro and custom Python code makes such a project a
relative doddl.  One can easily imagine building this size of device
into a cash register sized shell, perhaps with a suitably sized
touchscreen and drawer hardware interface, to build your own cash
register.  (Re touchscreen's I'm thinking of something from ELO
perhaps, see: http://www.elotouch.com/Products/Touchscreens/default.asp
-- I have a friend who is working on a kiosk using a normal ITX PC
mobo and that uses an ELO screen with a GNU/Linux software stack
behind it, so that's definitely possible...)

Cheers,

Walter

From emeraldoffice at hotmail.com  Mon Jan  2 21:20:23 2012
From: emeraldoffice at hotmail.com (Tamar Osher)
Date: Mon, 2 Jan 2012 14:20:23 -0600
Subject: [Tutor] want to chat with someone - phone, skype, or email
Message-ID: <BAY167-W41B61F5D69412979C2A136B9910@phx.gbl>


Hi!  I have never before learned a programming language, and I started learning Python a couple of days ago.  I am wondering: How does a person make the leap from reading about Python to doing Python?
There seems to be many fabulous online tutorials.  I have read all the info at tutorialspoint.com, but I am still sort of stuck.  I am reading another wonderful online tutorial.  But...
I would like to talk to someone.  I don't have any close friends who are computer programmers.  Does anyone want to briefly chat, and share their experiences about how they did it?
I hope to hear from you.  THANKS! 
>From Your Friend: Tamar Osher
Skype Name: tamarosher
Email: EmeraldOffice at hotmail.com
Message Phone Number: 011- 1- 513-252-2936





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

From rhettnaxel at gmail.com  Mon Jan  2 21:26:05 2012
From: rhettnaxel at gmail.com (Alexander)
Date: Mon, 2 Jan 2012 15:26:05 -0500
Subject: [Tutor] Touch Screen
In-Reply-To: <CANLXbfDnwbcXQRLaJX_EE=CtnQsg+DLKCW3dkOdF8+Wv3baCcA@mail.gmail.com>
References: <CANS6qmD4BeeoxKsitiywSKR37yFC9QEFTQ5=fpvkgYJX7nA9MQ@mail.gmail.com>
	<jdsrpn$ok$1@dough.gmane.org>
	<CANLXbfDnwbcXQRLaJX_EE=CtnQsg+DLKCW3dkOdF8+Wv3baCcA@mail.gmail.com>
Message-ID: <CANS6qmA4QW0K6T7LwbjeNGDexssAS46DxwWLhp3mw6EPOa07wA@mail.gmail.com>

On Mon, Jan 2, 2012 at 1:43 PM, Walter Prins <wprins at gmail.com> wrote:

> Hi,
>
> On 2 January 2012 18:07, Alan Gauld <alan.gauld at btinternet.com> wrote:
> > There may be a few cash registers rthat implemenmt their own embedded
> > hardware monitor but the cost of developing such a thing is so high
> > (especially compared to Linux!) that most devices like that use a
> regular OS
> > and just disguise it with a single app as the "desktop".
>
> Just to add to what Alan's said, and with apologies if appropriate as
> its arguably only tangentially relevant to your question, but you may
> be interested to keep an eye on the "Raspberry Pi", a 25$ computer
> (yes, $25) that's due for release in Jan 2012.  It will primarily use
> Python as programming language although others will be supported. (Not
> entirely suprising given that the OS is GNU/Linux.)  For more see
> here:
>
> http://en.wikipedia.org/wiki/Raspberry_Pi
>
> http://articles.businessinsider.com/2011-12-28/tech/30564049_1_computer-broadcom-foundation
> http://www.raspberrypi.org/faqs
>
> It seems that for anyone who wants to build his own device on the
> cheap from commodity hardware, something like this with a suitably
> configured Linux distro and custom Python code makes such a project a
> relative doddl.  One can easily imagine building this size of device
> into a cash register sized shell, perhaps with a suitably sized
> touchscreen and drawer hardware interface, to build your own cash
> register.  (Re touchscreen's I'm thinking of something from ELO
> perhaps, see: http://www.elotouch.com/Products/Touchscreens/default.asp
> -- I have a friend who is working on a kiosk using a normal ITX PC
> mobo and that uses an ELO screen with a GNU/Linux software stack
> behind it, so that's definitely possible...)
>
> Cheers,
>
> Walter
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Thanks for the replies gentlemen.
Walter, thank you for the Raspberry Pi introduction, it may very well help
me with my hobbies. I'll be certain to check it out as I develop my python
and development skills.
Thanks,
-- 
Alexander
7D9C597B
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120102/94eb311c/attachment-0001.html>

From eire1130 at gmail.com  Mon Jan  2 22:14:32 2012
From: eire1130 at gmail.com (eire1130 at gmail.com)
Date: Mon, 2 Jan 2012 21:14:32 +0000
Subject: [Tutor] want to chat with someone - phone, skype, or email
In-Reply-To: <BAY167-W41B61F5D69412979C2A136B9910@phx.gbl>
References: <BAY167-W41B61F5D69412979C2A136B9910@phx.gbl>
Message-ID: <1509686935-1325538875-cardhu_decombobulator_blackberry.rim.net-1100651738-@b5.c28.bise6.blackberry>


On the python site there is a tutorial called, something like, a non-programers guide to python. That is how I started to learn. I then bought somw beginer books. I then thought of some problems I wanted to solve and like eighteen months later I'm still working on those problems, but along the way I've learned a lot

Sorry, I won't skype with you as fun as that sounds =)

 Also I'm replying on my bb so I can't scroll to the bottom.



Sent from my Verizon Wireless BlackBerry

-----Original Message-----
From: Tamar Osher <emeraldoffice at hotmail.com>
Sender: tutor-bounces+eire1130=gmail.com at python.org
Date: Mon, 2 Jan 2012 14:20:23 
To: <tutor at python.org>
Subject: [Tutor] want to chat with someone - phone, skype, or email

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



From mlybrand at gmail.com  Mon Jan  2 22:22:19 2012
From: mlybrand at gmail.com (Mark Lybrand)
Date: Mon, 2 Jan 2012 13:22:19 -0800
Subject: [Tutor] want to chat with someone - phone, skype, or email
In-Reply-To: <BAY167-W41B61F5D69412979C2A136B9910@phx.gbl>
References: <BAY167-W41B61F5D69412979C2A136B9910@phx.gbl>
Message-ID: <CALsUBtwFp5bS3Ejkz-zZKZjjvRE1BiPiGOiEpZzHaxsh99LDCw@mail.gmail.com>

On Jan 2, 2012 12:22 PM, "Tamar Osher" <emeraldoffice at hotmail.com> wrote:
>
> Hi!  I have never before learned a programming language, and I started
learning Python a couple of days ago.  I am wondering: How does a person
make the leap from reading about Python to doing Python?

Not directly responding to the petition for chat opportunities, but to
making the leap.  What has helped me (started with python at the end of
november) was to find problems and apply python to them.  From a simple
password generator,to massage text files and databases.  Just last week my
colleagues asked me to give them some more info on python as one after
another problem gets solved. If you don't have an immediate problem make
one.  One final idea would be to google "python challenge". One problem
after another to complete a sort of scavenger hunt.

Mark
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120102/0cd00226/attachment.html>

From beachkidken at gmail.com  Mon Jan  2 23:00:47 2012
From: beachkidken at gmail.com (Ken G.)
Date: Mon, 02 Jan 2012 17:00:47 -0500
Subject: [Tutor] Which should it be, lists, tuples, dictionary or files?
Message-ID: <4F02290F.3070600@gmail.com>

I have been using an Open Office Spreadsheet containing basically, the 
food name, basic serving amount, calories, sodium and carbohydrate.  
Daily, I entered the servicing amount being eaten and its calculate the 
amount of calories, sodium and carbohydrate.  For some odd reason, I 
kept losing the spreadsheet and its data.

I am interested in keeping track of the number of calories consumed each 
day.  Due to losing the spreadsheet data so frequencies, I decided to 
use Python in keeping track of the basic information and perhaps, keep 
track of the calories in a file.

Over the last several months, numerous mention is made of lists, tuples 
and dictionary here.  Basically, the format will be as follow:

Name of Food
Basic Serving Amount
Calories per serving
Sodium per serving
Carbohydrate per serving

For example,

Name:  Hominy, Golden (3.5)
Serving Size:  1/2 cup
Calories:  100
Sodium:  380
Carbohydrate:  20

The '(3.5)' indicated above is number of servings in a 15.5-ounce can.  
It will not necessary be indicated.

Should the above five elements be stored as a list, tuples, dictionary 
or file?  I am will familiar with files and have some knowledge of using 
lists and tuples.  Not too familiar with dictionary.

Thank for any suggestion.

Ken





From steve at pearwood.info  Mon Jan  2 23:44:34 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 03 Jan 2012 09:44:34 +1100
Subject: [Tutor] want to chat with someone - phone, skype, or email
In-Reply-To: <BAY167-W41B61F5D69412979C2A136B9910@phx.gbl>
References: <BAY167-W41B61F5D69412979C2A136B9910@phx.gbl>
Message-ID: <4F023352.5030204@pearwood.info>

Tamar Osher wrote:
> Hi!  I have never before learned a programming language, and I started
> learning Python a couple of days ago.  I am wondering: How does a person
> make the leap from reading about Python to doing Python?

Open a terminal window, or an IDE, and start typing code.

That's it. There's no magic. You can read all the books you like, but 
eventually you need to type code. And then you are doing Python.

You say you have "read" the tutorials. But have you *done* the tutorials, 
actually typing code at a prompt and looking at the result?

If not, then do so. Reading is great, but there is absolutely no substitute 
for *doing*.


-- 
Steven

From steve at pearwood.info  Mon Jan  2 23:47:42 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 03 Jan 2012 09:47:42 +1100
Subject: [Tutor] Which should it be, lists, tuples, dictionary or files?
In-Reply-To: <4F02290F.3070600@gmail.com>
References: <4F02290F.3070600@gmail.com>
Message-ID: <4F02340E.2070300@pearwood.info>

Ken G. wrote:
> I have been using an Open Office Spreadsheet containing basically, the 
> food name, basic serving amount, calories, sodium and carbohydrate.  
> Daily, I entered the servicing amount being eaten and its calculate the 
> amount of calories, sodium and carbohydrate.  For some odd reason, I 
> kept losing the spreadsheet and its data.
> 
> I am interested in keeping track of the number of calories consumed each 
> day.  Due to losing the spreadsheet data so frequencies, I decided to 
> use Python in keeping track of the basic information and perhaps, keep 
> track of the calories in a file.

If you lose the spreadsheets, what makes you think you won't lose the Python 
files?

[...]
> Should the above five elements be stored as a list, tuples, dictionary 
> or file?  I am will familiar with files and have some knowledge of using 
> lists and tuples.  Not too familiar with dictionary.

If you to store the data permanently, it has to go into a file. I suggest you 
learn about INI files to start with. Start by googling for "INI file format" 
and see if it sounds like what you could use.



-- 
Steven


From alan.gauld at btinternet.com  Tue Jan  3 00:53:31 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 02 Jan 2012 23:53:31 +0000
Subject: [Tutor] want to chat with someone - phone, skype, or email
In-Reply-To: <BAY167-W41B61F5D69412979C2A136B9910@phx.gbl>
References: <BAY167-W41B61F5D69412979C2A136B9910@phx.gbl>
Message-ID: <jdtg1r$40i$1@dough.gmane.org>

On 02/01/12 20:20, Tamar Osher wrote:
> Hi! I have never before learned a programming language, and I started
> learning Python a couple of days ago. I am wondering: *How does a person
> make the leap from reading about Python to doing Python?*

You install Python and start typing in code rather than just reading it.
Then you modify the code and see if it does what you expected. Then 
modify it again. Add some new features to the examples in your tutor.

Also try following a mailing list (this one might be a good start!) or 
web forum. There are also a few good video tutorials for a change in style.

But mostly you just start writing code. As your confidence builds
try a project of your own - keep it simple to start with. No, I mean 
really simple! No, even simpler than that!

When things don't work as you expect - and they won't - read the 
documentation and experiment. If that doesn't help ask questions here.

FWIW you are not alone. I'm just in the process of (re-)learning 
Smalltalk using the Squeak environment and I'm doing exactly what I 
describe above. Typing in my book examples then modifying them.
When I get stuck I ask on the squeak-beginners list - and so far
get very few responses! (one up for Python!)

> I would like to talk to someone. I don't have any close friends who are
> computer programmers. Does anyone want to briefly chat, and share their
> experiences about how they did it?

This mailing list is full of people on the same journey. Feel free to 
share your questions and concerns. Even your frustrations. We might not 
resolve all of them but we will try to be helpful! :-)

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


From beachkidken at gmail.com  Tue Jan  3 01:31:22 2012
From: beachkidken at gmail.com (Ken G.)
Date: Mon, 02 Jan 2012 19:31:22 -0500
Subject: [Tutor] Which should it be, lists, tuples, dictionary or files?
In-Reply-To: <4F02340E.2070300@pearwood.info>
References: <4F02290F.3070600@gmail.com> <4F02340E.2070300@pearwood.info>
Message-ID: <4F024C5A.6030903@gmail.com>



On 01/02/2012 05:47 PM, Steven D'Aprano wrote:
> Ken G. wrote:
>> I have been using an Open Office Spreadsheet containing basically, 
>> the food name, basic serving amount, calories, sodium and 
>> carbohydrate.  Daily, I entered the servicing amount being eaten and 
>> its calculate the amount of calories, sodium and carbohydrate.  For 
>> some odd reason, I kept losing the spreadsheet and its data.
>>
>> I am interested in keeping track of the number of calories consumed 
>> each day.  Due to losing the spreadsheet data so frequencies, I 
>> decided to use Python in keeping track of the basic information and 
>> perhaps, keep track of the calories in a file.
>
> If you lose the spreadsheets, what makes you think you won't lose the 
> Python files?

I am using Open Office and for unknown reason, it does not always open.  
I am on Ubuntu 10.04.3 OS.  I use my Python files every day.
>
> [...]
>> Should the above five elements be stored as a list, tuples, 
>> dictionary or file?  I am will familiar with files and have some 
>> knowledge of using lists and tuples.  Not too familiar with dictionary.
>
> If you to store the data permanently, it has to go into a file. I 
> suggest you learn about INI files to start with. Start by googling for 
> "INI file format" and see if it sounds like what you could use.
Okay, thanks.  I will look into it.  Have not heard of INI file format.

Ken

From alan.gauld at btinternet.com  Tue Jan  3 02:24:11 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 03 Jan 2012 01:24:11 +0000
Subject: [Tutor] Which should it be, lists, tuples, dictionary or files?
In-Reply-To: <4F024C5A.6030903@gmail.com>
References: <4F02290F.3070600@gmail.com> <4F02340E.2070300@pearwood.info>
	<4F024C5A.6030903@gmail.com>
Message-ID: <jdtlbr$9m$1@dough.gmane.org>

On 03/01/12 00:31, Ken G. wrote:

>> If you to store the data permanently, it has to go into a file. I
>> suggest you learn about INI files to start with. Start by googling for
> Okay, thanks. I will look into it. Have not heard of INI file format.

It's a Microsoft text file format invented for use on Windows but
in fact is applicable to any kind of data stoorage with one or
two levels of key.

Another option for you would be a shelve.(See the shelve module
in the standard library) A file that acts like a dictionary.
You can store a list of values against a single key.

Alternatively a simple SqlLite database would give you general 
searchability if that is important.

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


From chayek777 at gmail.com  Tue Jan  3 02:52:57 2012
From: chayek777 at gmail.com (shane)
Date: Mon, 02 Jan 2012 20:52:57 -0500
Subject: [Tutor] Random number selection
Message-ID: <4F025F79.9020801@gmail.com>

I was wondering is there a way to have a variable generate a random 
integer each time the variable is called.
Ive tried random.randint(a,  b) and the range one to.
It selects a random number and assigns it to the variable
this part of the program would be math equations
with random number selections
x=ran  y=ran z=x*y
x * y = z
  s=input=('x*y= ')
    if s != z
There are many things I need to solve its my first program.
But I just need help on assigning a random number and looping through to 
get diff values for x and y


From d at davea.name  Tue Jan  3 03:36:05 2012
From: d at davea.name (Dave Angel)
Date: Mon, 02 Jan 2012 21:36:05 -0500
Subject: [Tutor] Random number selection
In-Reply-To: <4F025F79.9020801@gmail.com>
References: <4F025F79.9020801@gmail.com>
Message-ID: <4F026995.3050103@davea.name>

On 01/02/2012 08:52 PM, shane wrote:
> I was wondering is there a way to have a variable generate a random 
> integer each time the variable is called.
> Ive tried random.randint(a,  b) and the range one to.
> It selects a random number and assigns it to the variable
> this part of the program would be math equations
> with random number selections
> x=ran  y=ran z=x*y
> x * y = z
>  s=input=('x*y= ')
>    if s != z
> There are many things I need to solve its my first program.
> But I just need help on assigning a random number and looping through 
> to get diff values for x and y

There's so much wrong with that message I don't know how to respond.  
There is either a grammatical or syntax error on every line.

Variables with integer values are not 'called."  They also don't change 
values unless you change it.  So if you've got a loop, and you want them 
to have different values each time, then give them different values each 
time, by calling a function that does return a different value.

for ......
      x = random.randint(a,b)
      y = random.randint(a,b)
      ...  do something with the values



-- 

DaveA


From wprins at gmail.com  Tue Jan  3 08:18:03 2012
From: wprins at gmail.com (Walter Prins)
Date: Tue, 3 Jan 2012 07:18:03 +0000
Subject: [Tutor] Which should it be, lists, tuples, dictionary or files?
In-Reply-To: <jdtlbr$9m$1@dough.gmane.org>
References: <4F02290F.3070600@gmail.com> <4F02340E.2070300@pearwood.info>
	<4F024C5A.6030903@gmail.com> <jdtlbr$9m$1@dough.gmane.org>
Message-ID: <CANLXbfB81Mh8ESjHYYa43dAESiMqVUmfBehy2umsVJkv95sDJQ@mail.gmail.com>

Hi Ken,

On 3 January 2012 01:24, Alan Gauld <alan.gauld at btinternet.com> wrote:
>>> If you to store the data permanently, it has to go into a file. I
>>> suggest you learn about INI files to start with. Start by googling for
>>
>> Okay, thanks. I will look into it. Have not heard of INI file format.
>
>
> It's a Microsoft text file format invented for use on Windows but
> in fact is applicable to any kind of data stoorage with one or
> two levels of key.

Just to add:  The Python "ConfigParser" class, in the configparser
module, that is part of the Python standard library, allows you to
easily interact with INI file like files.  See here:
http://docs.python.org/library/configparser.html
http://wiki.python.org/moin/ConfigParserExamples

There is also ConfigObj, which is superior to ConfigParser and amongst
other things allows nested sections to any depth (limited by what the
machine allows of course;) ):
http://www.voidspace.org.uk/python/configobj.html
http://www.voidspace.org.uk/python/articles/configobj.shtml

All of that said, I'm slightly worried about your spreadsheet issues
-- you should not be having such issues really...   Perhaps you should
consider updating/upgrading your system or try to figure out why OOO
is giving yous so much trouble?  Re-inventing what you have in yoru
spreadsheet by means of INI files seem slightly the wrong way to solve
your stated problem somehow! :)

Cheers,

Walter

From jeanpierreda at gmail.com  Tue Jan  3 08:31:45 2012
From: jeanpierreda at gmail.com (Devin Jeanpierre)
Date: Tue, 3 Jan 2012 02:31:45 -0500
Subject: [Tutor] Which should it be, lists, tuples, dictionary or files?
In-Reply-To: <jdtlbr$9m$1@dough.gmane.org>
References: <4F02290F.3070600@gmail.com> <4F02340E.2070300@pearwood.info>
	<4F024C5A.6030903@gmail.com> <jdtlbr$9m$1@dough.gmane.org>
Message-ID: <CABicbJ+5=7vtJWvL3aAJFWZkLt+g6tvTTT6t03vZvd9mBYbHwg@mail.gmail.com>

> Another option for you would be a shelve.(See the shelve module
> in the standard library) A file that acts like a dictionary.
> You can store a list of values against a single key.

It's probably worth mentioning that shelve is not secure; loading a
saved shelf can involve executing arbitrary python code embedded
inside it. This probably isn't important for this particular project,
but maybe in the future, if you consider using shelf for something
more security-conscious...

-- Devin

On Mon, Jan 2, 2012 at 8:24 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 03/01/12 00:31, Ken G. wrote:
>
>>> If you to store the data permanently, it has to go into a file. I
>>> suggest you learn about INI files to start with. Start by googling for
>>
>> Okay, thanks. I will look into it. Have not heard of INI file format.
>
>
> It's a Microsoft text file format invented for use on Windows but
> in fact is applicable to any kind of data stoorage with one or
> two levels of key.
>
> Another option for you would be a shelve.(See the shelve module
> in the standard library) A file that acts like a dictionary.
> You can store a list of values against a single key.
>
> Alternatively a simple SqlLite database would give you general searchability
> if that is important.
>
> --
> Alan G
> 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 steve at pearwood.info  Tue Jan  3 11:57:50 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 03 Jan 2012 21:57:50 +1100
Subject: [Tutor] Random number selection
In-Reply-To: <4F026995.3050103@davea.name>
References: <4F025F79.9020801@gmail.com> <4F026995.3050103@davea.name>
Message-ID: <4F02DF2E.5080606@pearwood.info>

Dave Angel wrote:

> Variables with integer values are not 'called."  They also don't change 
> values unless you change it.  So if you've got a loop, and you want them 
> to have different values each time, then give them different values each 
> time, by calling a function that does return a different value.

In fairness, some programming communities call instance attributes "variables" 
(which annoys me no end, but it is common), and computed attributes 
("variables") can get a different value each time you look them up. So if you 
can have this:

instance = MyClass()
instance.x  # x is a computed "instance variable" (blah, I hate that term)
=> gives 23
instance.x
=> gives 42


then in principle it isn't a stupid idea to have this too:

x = MyVariable()
x
=> gives 23
x
=> gives 42


I don't know any language that operates like that, and it is probably a bad 
idea in practice, but the principle isn't entirely crazy.

It's also an *incredibly* common thought -- I have seen so many people assume 
that after doing this once:

x = random(1, 100)

x will now have a different random number each time you look at it. Which kind 
of makes sense, if you think of x as a variable that varies on its own instead 
of something which can be varied.


-- 
Steven

From alan.gauld at btinternet.com  Tue Jan  3 12:28:36 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 03 Jan 2012 11:28:36 +0000
Subject: [Tutor] Which should it be, lists, tuples, dictionary or files?
In-Reply-To: <CABicbJ+5=7vtJWvL3aAJFWZkLt+g6tvTTT6t03vZvd9mBYbHwg@mail.gmail.com>
References: <4F02290F.3070600@gmail.com> <4F02340E.2070300@pearwood.info>
	<4F024C5A.6030903@gmail.com> <jdtlbr$9m$1@dough.gmane.org>
	<CABicbJ+5=7vtJWvL3aAJFWZkLt+g6tvTTT6t03vZvd9mBYbHwg@mail.gmail.com>
Message-ID: <jduop4$63d$1@dough.gmane.org>

On 03/01/12 07:31, Devin Jeanpierre wrote:

> It's probably worth mentioning that shelve is not secure; loading a
> saved shelf can involve executing arbitrary python code embedded
> inside it. This probably isn't important for this particular project,
> but maybe in the future, if you consider using shelf for something
> more security-conscious...

A good point, shelve should be treated more like an internal persistence 
tool than a general purpose database. It's
fine if you know what you are storing but if random data
is being put into it there could be problems.

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


From alan.gauld at btinternet.com  Tue Jan  3 12:44:11 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 03 Jan 2012 11:44:11 +0000
Subject: [Tutor] Random number selection
In-Reply-To: <4F025F79.9020801@gmail.com>
References: <4F025F79.9020801@gmail.com>
Message-ID: <jdupmc$crv$1@dough.gmane.org>

On 03/01/12 01:52, shane wrote:
> I was wondering is there a way to have a variable generate a random
> integer each time the variable is called.

You can call a function to assign a value to a variable,
but you can't "call" a variable (unless its assigned to
a function but that's another subject entirely!).

> Ive tried random.randint(a, b) and the range one to.
> It selects a random number and assigns it to the variable

Yes, that's what it's supposed to do. So where do you have a problem?

> this part of the program would be math equations
> with random number selections
> x=ran y=ran z=x*y

In Python that translates to

x = random.randint(a,b)
y = random.randint(a,b)
z = x*y

> x * y = z

But this doesn't make sense unless you mean an equality test. In which 
case in Python it's written:

x*y == z

and given the code above should equate to True

> s=input=('x*y= ')

Too many equal signs there. I assume you mean

s = input("x*y= ")

Which will assign a string value from the user to s(*). I'm not sure 
what you think the string will contain? The letter 'z' maybe? or some 
arbitrary number that you need to factorise to come up with new x,y 
values? I can only guess. I'll assume the second option - a string 
version of a number

(*) I'm assuming you are using Python version 3? If not input
could return a number rather than a string but since input()
is not secure we generally recommend you don;pt use it in
version 2.


> if s != z

z is a number, s a string so  you need to convert:

if int(s) != z:

> There are many things I need to solve its my first program.

True, but at the moment I don't think we understand what
it is you are trying to do.

> But I just need help on assigning a random number and looping through to
> get diff values for x and y

A random number or multiple random numbers?
And do you want the random numbers assigned to x,y or something else?
And "looping through" what?

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


From beachkidken at gmail.com  Tue Jan  3 13:19:05 2012
From: beachkidken at gmail.com (Ken G.)
Date: Tue, 03 Jan 2012 07:19:05 -0500
Subject: [Tutor] Which should it be, lists, tuples,
 dictionary or files? [SOLVED]
In-Reply-To: <jduop4$63d$1@dough.gmane.org>
References: <4F02290F.3070600@gmail.com>
	<4F02340E.2070300@pearwood.info>	<4F024C5A.6030903@gmail.com>
	<jdtlbr$9m$1@dough.gmane.org>	<CABicbJ+5=7vtJWvL3aAJFWZkLt+g6tvTTT6t03vZvd9mBYbHwg@mail.gmail.com>
	<jduop4$63d$1@dough.gmane.org>
Message-ID: <4F02F239.7080207@gmail.com>

On 01/03/2012 06:28 AM, Alan Gauld wrote:
> On 03/01/12 07:31, Devin Jeanpierre wrote:
>
>> It's probably worth mentioning that shelve is not secure; loading a
>> saved shelf can involve executing arbitrary python code embedded
>> inside it. This probably isn't important for this particular project,
>> but maybe in the future, if you consider using shelf for something
>> more security-conscious...
>
> A good point, shelve should be treated more like an internal 
> persistence tool than a general purpose database. It's
> fine if you know what you are storing but if random data
> is being put into it there could be problems.
>
My thanks to all of those who replied and offered suggestions.  I will 
be looking into every one of those suggestions.  Again, my thanks.  This 
is truly a great Python group.

Ken, Louisville, KY, USA

From bugcy013 at gmail.com  Tue Jan  3 15:13:29 2012
From: bugcy013 at gmail.com (Ganesh Kumar)
Date: Tue, 3 Jan 2012 19:43:29 +0530
Subject: [Tutor] Parse multi line with re module.
Message-ID: <CAJzooYdBNYmYRChySBhAHymd_+e_D-7yTG9juC0+__1BJ-Qr3w@mail.gmail.com>

Hi Guys,

I want parse multiple line. with re.module, this is my given string
http://dpaste.com/680760/ I have try with re.compile module. I want parse
two line mac address and channel,
I have done with for mac address finding

r = re.compile("^Searching for OPUSH on (\w\w(:\w\w)+)")

for channel finding

device_r = re.compile("^Channel: (\d+)")

the two parsing string working. but I want combine two pattern in to one.

This is my code
http://www.bpaste.net/show/21323/

please guide me .


-Ganesh

Did I learn something today? If not, I wasted it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120103/35ac7f3c/attachment.html>

From joel.goldstick at gmail.com  Tue Jan  3 16:21:48 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 3 Jan 2012 10:21:48 -0500
Subject: [Tutor] Parse multi line with re module.
In-Reply-To: <CAJzooYdBNYmYRChySBhAHymd_+e_D-7yTG9juC0+__1BJ-Qr3w@mail.gmail.com>
References: <CAJzooYdBNYmYRChySBhAHymd_+e_D-7yTG9juC0+__1BJ-Qr3w@mail.gmail.com>
Message-ID: <CAPM-O+zK9Botu3GaccPBgStP=4_EF6vo5f6dm7_0H5j2+yDJ8g@mail.gmail.com>

On Tue, Jan 3, 2012 at 9:13 AM, Ganesh Kumar <bugcy013 at gmail.com> wrote:
> Hi Guys,
>
> I want parse multiple line. with re.module, this is my given string
> http://dpaste.com/680760/ I have try with re.compile module. I want parse
> two line mac address and channel,
> I have done with for mac address finding
>
> r = re.compile("^Searching for OPUSH on (\w\w(:\w\w)+)")
>
> for channel finding
>
> device_r = re.compile("^Channel: (\d+)")
>
> the two parsing string working. but I want combine two pattern in to one.
>
> This is my code
> http://www.bpaste.net/show/21323/
>
> please guide me .
>
>
> -Ganesh
>
> Did I learn something today? If not, I wasted it.
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 


Do you know about str.startswith()
http://docs.python.org/library/stdtypes.html#str.startswith

Since your data is so well defined I think it would be simpler to just
read each line, strip whitespace, use startswith() to check for
"Searching for OPUSH on" and "Channel:"

You can slice to pull out the mac address and the channel number like so:

>>> s = "Searching for OPUSH on 00:1D:FD:06:99:99"
>>> s[23:]
'00:1D:FD:06:99:99'   # this will work if no other text follows the mac address
>>> s[23:41]
'00:1D:FD:06:99:99' # this will work to just capture the mac address
>>>

For the Channel number, after stripping whitespace, take the slice from s[9:]

Searching for OPUSH on 00:1D:FD:06:99:99 ...
    Channel: 9

Joel Goldstick

From jsantos.lazer at gmail.com  Tue Jan  3 18:44:08 2012
From: jsantos.lazer at gmail.com (Joaquim Santos)
Date: Tue, 3 Jan 2012 17:44:08 +0000
Subject: [Tutor] Still the Python Challenge
In-Reply-To: <CAPC6GuKsQ4Q=wAgq=vyA6OsB74-uJ+nSaudHj2FwEz7sqom39w@mail.gmail.com>
References: <CAPC6GuKsQ4Q=wAgq=vyA6OsB74-uJ+nSaudHj2FwEz7sqom39w@mail.gmail.com>
Message-ID: <CAPC6GuLaNTrtHXfwJDpBBsCR7iy5gAzat0D74rAcBKA3+nsPvg@mail.gmail.com>

Hi list!

After this past week of no PC and no work, I'm again at the Python
Challenge Cypher problem.
I decided to go with the flow and solve it with maketrans (6 lines of
code against the 40 and going I had already...) and it solved it
quickly and clean!

However, and please be sure I don't want to re-invent any wheel, I
still got some doubts unexplained...

?- How to correctly populate a list using, for instance, a for loop;

?- how to correctly use join to read the said list in a human friendly way...

This was the code I was using.

for letter in cypheredText:

asciiValue = ord(letter)

if asciiValue in range(97, 123):

asciiValue += shiftedCypherNumber

if asciiValue > 122:

asciiValue -= 26

newLetter = chr(asciiValue)

text = list()

text.append(newLetter)

joinedText = ' '.join(text)

return joinedText


Thanks for all your time and patience. Sorry for before not using Plain text!



Joaquim Santos

From robert.sjoblom at gmail.com  Tue Jan  3 18:51:43 2012
From: robert.sjoblom at gmail.com (Robert Sjoblom)
Date: Tue, 3 Jan 2012 18:51:43 +0100
Subject: [Tutor] Parse multi line with re module.
In-Reply-To: <CAPM-O+zK9Botu3GaccPBgStP=4_EF6vo5f6dm7_0H5j2+yDJ8g@mail.gmail.com>
References: <CAJzooYdBNYmYRChySBhAHymd_+e_D-7yTG9juC0+__1BJ-Qr3w@mail.gmail.com>
	<CAPM-O+zK9Botu3GaccPBgStP=4_EF6vo5f6dm7_0H5j2+yDJ8g@mail.gmail.com>
Message-ID: <CAJKU7g1s9Npi2apSa6Qo_8LhCDHtG1Q5sFwJTR4g--XSwZQChA@mail.gmail.com>

On 3 January 2012 16:21, Joel Goldstick <joel.goldstick at gmail.com> wrote:
> --

Joel, when you start your emails with this (two dashes) some email
readers (gmail among them) will think you're ending your email; I have
to expand your post because it thinks that what is hidden is the
signature. Just thought you should know.


-- 
best regards,
Robert S.

From alan.gauld at btinternet.com  Tue Jan  3 20:09:03 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 03 Jan 2012 19:09:03 +0000
Subject: [Tutor] Still the Python Challenge
In-Reply-To: <CAPC6GuLaNTrtHXfwJDpBBsCR7iy5gAzat0D74rAcBKA3+nsPvg@mail.gmail.com>
References: <CAPC6GuKsQ4Q=wAgq=vyA6OsB74-uJ+nSaudHj2FwEz7sqom39w@mail.gmail.com>
	<CAPC6GuLaNTrtHXfwJDpBBsCR7iy5gAzat0D74rAcBKA3+nsPvg@mail.gmail.com>
Message-ID: <jdvjog$cm0$1@dough.gmane.org>

On 03/01/12 17:44, Joaquim Santos wrote:

>   - How to correctly populate a list using, for instance, a for loop;
>

I can't tell what you had because the formatting got lost in the email 
ether...

>   - how to correctly use join to read the said list in a human friendly way...

You seem to be doing that OK as is. Do you think you have a problem with it?

> This was the code I was using.
>
> for letter in cypheredText:
>
> asciiValue = ord(letter)
>
> if asciiValue in range(97, 123):
>
> asciiValue += shiftedCypherNumber
>
> if asciiValue>  122:
>
> asciiValue -= 26
>
> newLetter = chr(asciiValue)
>

Up to her is OK, but...

Asssuming this next line is still inside the for loop?

> text = list()

If this is in the loop then you create a new list for every letter.
And you override the previous one so losing it...
You probably want this before the loop. Its more usual to just do

text = []

though.... But both techniques work.

> text.append(newLetter)
>
> joinedText = ' '.join(text)

This is right but your text only has a single value in it
as explained above.

> Thanks for all your time and patience. Sorry for before not using Plain text!

It seems something is still broken! :-(

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


From joel.goldstick at gmail.com  Tue Jan  3 20:20:18 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 3 Jan 2012 14:20:18 -0500
Subject: [Tutor] Parse multi line with re module.
In-Reply-To: <CAJKU7g1s9Npi2apSa6Qo_8LhCDHtG1Q5sFwJTR4g--XSwZQChA@mail.gmail.com>
References: <CAJzooYdBNYmYRChySBhAHymd_+e_D-7yTG9juC0+__1BJ-Qr3w@mail.gmail.com>
	<CAPM-O+zK9Botu3GaccPBgStP=4_EF6vo5f6dm7_0H5j2+yDJ8g@mail.gmail.com>
	<CAJKU7g1s9Npi2apSa6Qo_8LhCDHtG1Q5sFwJTR4g--XSwZQChA@mail.gmail.com>
Message-ID: <CAPM-O+wootbkXuNwWZAaevPmuacGF=QaKL=10gOjzgfNKc6Pew@mail.gmail.com>

On Tue, Jan 3, 2012 at 12:51 PM, Robert Sjoblom
<robert.sjoblom at gmail.com> wrote:
> On 3 January 2012 16:21, Joel Goldstick <joel.goldstick at gmail.com> wrote:
>> --
>
> Joel, when you start your emails with this (two dashes) some email
> readers (gmail among them) will think you're ending your email; I have
> to expand your post because it thinks that what is hidden is the
> signature. Just thought you should know.
>
>
> --
> best regards,
> Robert S.

Thank you.  I'm not sure how that happens.  I'll check my signature.


Joel Goldstick

From james.homme at highmark.com  Tue Jan  3 21:44:28 2012
From: james.homme at highmark.com (Homme, James)
Date: Tue, 3 Jan 2012 20:44:28 +0000
Subject: [Tutor] Primitive Chess Clock Program Question
Message-ID: <BF85B26B8ED7B647ACAD9C68E89DA5540D888170@HMBREXMP03.highmark.com>

Hi,
So far, I know about raw_input as a way to get something from the keyboard into my program. My question is this. Let's say I am trying to subtract time from a value as though someone is thinking and they want to type in a move. If my program prints a prompt to the screen, while the person is thinking, is it still running, or is it asleep?

Another way to put this is, can my program use one of the functions in datetime to keep ticking off seconds for itself, but not show them to the user while it's waiting for input, or do I need to simply check the time after they type their move in, then update the clock at that point?

Thanks.

Jim

Jim Homme,
Usability Services,
Phone: 412-544-1810.


________________________________

This e-mail and any attachments to it are confidential and are intended solely for use of the individual or entity to whom they are addressed. If you have received this e-mail in error, please notify the sender immediately and then delete it. If you are not the intended recipient, you must not keep, use, disclose, copy or distribute this e-mail without the author's prior permission. The views expressed in this e-mail message do not necessarily represent the views of Highmark Inc., its subsidiaries, or affiliates.

From steve at pearwood.info  Tue Jan  3 22:20:29 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 04 Jan 2012 08:20:29 +1100
Subject: [Tutor] Still the Python Challenge
In-Reply-To: <CAPC6GuLaNTrtHXfwJDpBBsCR7iy5gAzat0D74rAcBKA3+nsPvg@mail.gmail.com>
References: <CAPC6GuKsQ4Q=wAgq=vyA6OsB74-uJ+nSaudHj2FwEz7sqom39w@mail.gmail.com>
	<CAPC6GuLaNTrtHXfwJDpBBsCR7iy5gAzat0D74rAcBKA3+nsPvg@mail.gmail.com>
Message-ID: <4F03711D.5010006@pearwood.info>

Joaquim Santos wrote:
> Hi list!
> 
> After this past week of no PC and no work, I'm again at the Python
> Challenge Cypher problem.
> I decided to go with the flow and solve it with maketrans (6 lines of
> code against the 40 and going I had already...) and it solved it
> quickly and clean!
> 
> However, and please be sure I don't want to re-invent any wheel, I
> still got some doubts unexplained...
> 
>  - How to correctly populate a list using, for instance, a for loop;


In general:

mylist = []
for value in some_sequence:
     mylist.append( process(value) )


Here's a concrete example: take a list of words, convert to lower case, and 
make them plural:

words = ['CAT', 'DOG', 'TREE', 'CAR', 'PENCIL']
plurals = []
for word in words:
     word = word.lower()
     plurals.append(word + 's')

print(plurals)



>  - how to correctly use join to read the said list in a human friendly way...


I don't understand this question. You can't use join to read a list. Perhaps 
you mean to use join to print a list? Specifically, you use join to build a 
single string from a list of sub-strings.

Given plurals above, we can build a single list of words separated by double 
spaces and a hyphen:

print('  -  '.join(plurals))


To join a list of single characters into a string, use join on the empty 
string. Compare:

chars = ['a', 'b', 'c', 'd']
print(' '.join(chars))
print(''.join(chars))




-- 
Steven

From steve at pearwood.info  Tue Jan  3 22:28:33 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 04 Jan 2012 08:28:33 +1100
Subject: [Tutor] Primitive Chess Clock Program Question
In-Reply-To: <BF85B26B8ED7B647ACAD9C68E89DA5540D888170@HMBREXMP03.highmark.com>
References: <BF85B26B8ED7B647ACAD9C68E89DA5540D888170@HMBREXMP03.highmark.com>
Message-ID: <4F037301.60800@pearwood.info>

Homme, James wrote:
> Hi,
> So far, I know about raw_input as a way to get something from the keyboard into my program. My question is this. Let's say I am trying to subtract time from a value as though someone is thinking and they want to type in a move. If my program prints a prompt to the screen, while the person is thinking, is it still running, or is it asleep?

raw_input blocks for as long as it takes for the user to type something and 
press Enter. If they take an hour, raw_input will wait an hour.

I assume you want to display something like this:

Enter your next move: 0:30

where the "0:30" is the time remaining, and is constantly updating. When it 
hits zero, the function returns whether the user has typed anything or not.

Oooh, this is a cunning problem! I like it. But I have no idea how to solve 
it. I'm going to have to do some research, in my Copious Spare Time.


-- 
Steven


From alan.gauld at btinternet.com  Wed Jan  4 02:22:42 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 04 Jan 2012 01:22:42 +0000
Subject: [Tutor] Primitive Chess Clock Program Question
In-Reply-To: <4F037301.60800@pearwood.info>
References: <BF85B26B8ED7B647ACAD9C68E89DA5540D888170@HMBREXMP03.highmark.com>
	<4F037301.60800@pearwood.info>
Message-ID: <je09l2$ua$1@dough.gmane.org>

On 03/01/12 21:28, Steven D'Aprano wrote:

> I assume you want to display something like this:
>
> Enter your next move: 0:30
>
> where the "0:30" is the time remaining, and is constantly updating. When
> it hits zero, the function returns whether the user has typed anything
> or not.

Assuming Steven has guessed right then I think you need to use one of 
the non blocking input mechanisms like kbhit() or getch() or somesuch.

Those methods are notioriously unreliable and OS specific. For example 
you may need to use curses or the Microsoft runtime module msvcrt.

The general code will look like

Display prompt
while no key hit
     sleep briefly
     update time in prompt
     (using ctrl characters to delete/overwrire previouis entry)
#when key hit
process input.

It is a non trivial problem and the details will depend on whether you 
use curses or the microsoft route.

It is one of those few cases that is actually much easier to do
in a GUI. GUIs generally make life more complex but in this case 
updating a label while awaiting user input is almost trivial
(for a GUI).

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


From daedae11 at 126.com  Wed Jan  4 12:43:59 2012
From: daedae11 at 126.com (daedae11)
Date: Wed, 4 Jan 2012 19:43:59 +0800
Subject: [Tutor] question about the exercises in <core python programing>
Message-ID: <201201041943596023545@126.com>

Who can give me an example program about the exercise 4 in chapter 9 in <core python programming> ?




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

From daedae11 at 126.com  Wed Jan  4 12:53:42 2012
From: daedae11 at 126.com (daedae11)
Date: Wed, 4 Jan 2012 19:53:42 +0800
Subject: [Tutor] question about the exercises in <core python programing>
Message-ID: <201201041953421769560@126.com>

Who can give me an example program about the exercise 4 in chapter 9 in <core python programming> ?

Thank you!




daedae11
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120104/5b7734e2/attachment.html>

From wprins at gmail.com  Wed Jan  4 14:11:35 2012
From: wprins at gmail.com (Walter Prins)
Date: Wed, 4 Jan 2012 13:11:35 +0000
Subject: [Tutor] question about the exercises in <core python programing>
In-Reply-To: <201201041953421769560@126.com>
References: <201201041953421769560@126.com>
Message-ID: <CANLXbfDg8Xgb0+XQj58J2Op6yLyNngiwpj_bZ6iSb=ZAfsHiWw@mail.gmail.com>

Hi daedae11,

2012/1/4 daedae11 <daedae11 at 126.com>:
> Who can give me an example program?about the exercise 4 in chapter 9 in
> <core python programming> ?
>
> Thank you!

You're limiting the number of people who might help you by not posting
the excercise/problem you're having directly and instead only giving a
reference to a book the readers of your message may not have.
(Probably not, judging by the lack of responses so far.)

Please post details of the excercise, what you've tried, what happened
as a result (including any errors messages and stack traces as
appropriate), and what you expected should've happened.  This will
ensure people have all the required information to help you directly
without having to spend time hunting down material and/or having to
guess at or extract from you what problem(s) you're having.

Thanks

Walter

From daedae11 at 126.com  Wed Jan  4 14:30:32 2012
From: daedae11 at 126.com (daedae11)
Date: Wed, 4 Jan 2012 21:30:32 +0800
Subject: [Tutor] question about the an exercise in <core python programing>
	(including the discription about the exercise)
Message-ID: <2012010421303227579114@126.com>

Who can give me an example program about the exercise 6 in chapter 9 in <core python programming> ?

The exercise is:
Write a program that compare the two files given by users. If the two files' content is equal, just print "equal". Else, print the rows And column number of the first different position.

Thank you!





Thank you!




daedae11
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120104/2c845be4/attachment.html>

From dpalao.python at gmail.com  Wed Jan  4 15:13:23 2012
From: dpalao.python at gmail.com (David Palao)
Date: Wed, 4 Jan 2012 15:13:23 +0100
Subject: [Tutor] question about the an exercise in <core python
 programing> (including the discription about the exercise)
In-Reply-To: <2012010421303227579114@126.com>
References: <2012010421303227579114@126.com>
Message-ID: <CAKUKWzn152jq-x+H1bC_2Z9-4TA9=OHLpieZdsBJ+iYg5LvwWQ@mail.gmail.com>

Hi,
some hints:
1) strings are iterables
2) help(zip)
3) help(enumerate)

Best regards.

2012/1/4 daedae11 <daedae11 at 126.com>

> **
> Who can give me an example program about the exercise 6 in chapter 9 in
> <core python programming> ?
>
> The exercise is:
> Write a program that compare the two files given by users. If the two
> files' content is equal, just print "equal". Else, print the rows And
> column number of the first different position.
>
> Thank you!
>
>
>
>
>
> Thank you!
>
> ------------------------------
> daedae11
>
> _______________________________________________
> 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/20120104/0843e93d/attachment.html>

From alan.gauld at btinternet.com  Wed Jan  4 15:36:57 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 04 Jan 2012 14:36:57 +0000
Subject: [Tutor] question about the an exercise in <core python
 programing> (including the discription about the exercise)
In-Reply-To: <CAKUKWzn152jq-x+H1bC_2Z9-4TA9=OHLpieZdsBJ+iYg5LvwWQ@mail.gmail.com>
References: <2012010421303227579114@126.com>
	<CAKUKWzn152jq-x+H1bC_2Z9-4TA9=OHLpieZdsBJ+iYg5LvwWQ@mail.gmail.com>
Message-ID: <je1o69$sl9$1@dough.gmane.org>

On 04/01/12 14:13, David Palao wrote:
> Hi,
> some hints:
> 1) strings are iterables

And so are files.... ;-)

> 2) help(zip)
> 3) help(enumerate)

>     Write a program that compare the two files given by users. If the
>     two files' content is equal, just print "equal". Else, print the
>     rows And column number of the first different position.

In pseudocode you could do:

f1 = open(file1)
f2 = open(file2)
lineNum = 1
while True:
    line = f1.readline()
    if line != f2.readline():
         print lineNum, " : ", line
         exit
    else:
        lineNum += 1
print "equal"


But there other approaches you could use.

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


From joel.goldstick at gmail.com  Wed Jan  4 15:54:14 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Wed, 4 Jan 2012 09:54:14 -0500
Subject: [Tutor] question about the an exercise in <core python
 programing> (including the discription about the exercise)
In-Reply-To: <je1o69$sl9$1@dough.gmane.org>
References: <2012010421303227579114@126.com>
	<CAKUKWzn152jq-x+H1bC_2Z9-4TA9=OHLpieZdsBJ+iYg5LvwWQ@mail.gmail.com>
	<je1o69$sl9$1@dough.gmane.org>
Message-ID: <CAPM-O+xGzQ2etn6WVX0UuJ-KVydseE-B+xZhU0zjkr1yvtGaHw@mail.gmail.com>

On Wed, Jan 4, 2012 at 9:36 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 04/01/12 14:13, David Palao wrote:
>>
>> Hi,
>> some hints:
>> 1) strings are iterables
>
>
> And so are files.... ;-)
>
>> 2) help(zip)
>> 3) help(enumerate)
>
>
>> ? ?Write a program that compare the two files given by users. If the
>> ? ?two files' content is equal, just print "equal". Else, print the
>> ? ?rows And column number of the first different position.
>
>
> In pseudocode you could do:
>
> f1 = open(file1)
> f2 = open(file2)
> lineNum = 1
> while True:
> ? line = f1.readline()
# I would change next line to this:
     line2 = f2.readline()    # this to have a name for each line for below
     if line != line2:
> ? if line != f2.readline():
> ? ? ? ?print lineNum, " : ", line

# in here I believe you need a bit more.  You now know the lines are
not equal, but the exercise requires the line number and column number
where the two lines differ
# To do that, you need to do something similar to what Alan has shown
    for i, c in enumerate(line):      #enumerate iterates over the
characters in line, and returns the index and the character
          if line2[i] != c:                  # line2[i] is the
character in the same position on the line as c from line
              print "The file differs at line %d, column %d" % lineNum, i
> ? ? ? ?exit
> ? else:
> ? ? ? lineNum += 1
> print "equal"
>
>
> But there other approaches you could use.
>
> --
> Alan G
> 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



-- 


Joel Goldstick

From alan.gauld at btinternet.com  Wed Jan  4 18:44:25 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 04 Jan 2012 17:44:25 +0000
Subject: [Tutor] question about the an exercise in <core python
 programing> (including the discription about the exercise)
In-Reply-To: <CAPM-O+xGzQ2etn6WVX0UuJ-KVydseE-B+xZhU0zjkr1yvtGaHw@mail.gmail.com>
References: <2012010421303227579114@126.com>
	<CAKUKWzn152jq-x+H1bC_2Z9-4TA9=OHLpieZdsBJ+iYg5LvwWQ@mail.gmail.com>
	<je1o69$sl9$1@dough.gmane.org>
	<CAPM-O+xGzQ2etn6WVX0UuJ-KVydseE-B+xZhU0zjkr1yvtGaHw@mail.gmail.com>
Message-ID: <je235p$jgv$1@dough.gmane.org>

On 04/01/12 14:54, Joel Goldstick wrote:

>>>     two files' content is equal, just print "equal". Else, print the
>>>     rows And column number of the first different position.

>> while True:
>>    line = f1.readline()
>>    if line != f2.readline():
>>         print lineNum, " : ", line
>
> # in here I believe you need a bit more.  You now know the lines are
> not equal, but the exercise requires the line number and column number

Oops, I didn't notice the column bit...sorry.

> # To do that, you need to do something similar to what Alan has shown
>      for i, c in enumerate(line):      #enumerate iterates over the
>            if line2[i] != c:                  # line2[i] is the
>                print "The file differs at line %d, column %d" % lineNum, i

Yep, that ought to work.

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


From bbbgggwww at gmail.com  Wed Jan  4 19:28:40 2012
From: bbbgggwww at gmail.com (brandon w)
Date: Wed, 4 Jan 2012 13:28:40 -0500
Subject: [Tutor] How to Capture a key being pressed?
Message-ID: <CAKXQjyW6pDCdpd1L1XqvFQSxM67266-x6Un231BYcGHrMtVdOQ@mail.gmail.com>

How do I capture a key like the <Space> bar or the <Enter> key? Is there
anything that comes in the default Python2.6.6 installation?
I have found something called "termios" doing a search. Should I just use
Pygame? I would like it to go cross platform if possible.

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

From alan.gauld at btinternet.com  Wed Jan  4 20:05:28 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 04 Jan 2012 19:05:28 +0000
Subject: [Tutor] How to Capture a key being pressed?
In-Reply-To: <CAKXQjyW6pDCdpd1L1XqvFQSxM67266-x6Un231BYcGHrMtVdOQ@mail.gmail.com>
References: <CAKXQjyW6pDCdpd1L1XqvFQSxM67266-x6Un231BYcGHrMtVdOQ@mail.gmail.com>
Message-ID: <je27to$m2s$1@dough.gmane.org>

On 04/01/12 18:28, brandon w wrote:
> How do I capture a key like the <Space> bar or the <Enter> key?

It depends on your OS.

For Windows use msvcrt and the getch() function.

For other OS your best bet is curses.

See the "Event Handling" topic in my tutorial for examples
using both.

There is a terminal module that tries to hide the differences.
There is also a 3rd party module tat offers more functionality on Windows.

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


From brianjamesarb at gmail.com  Thu Jan  5 04:48:57 2012
From: brianjamesarb at gmail.com (brian arb)
Date: Wed, 4 Jan 2012 22:48:57 -0500
Subject: [Tutor] Your thoughts on designing python code for unit testing?
Message-ID: <CABYizF+xiXurMtvnj3g3ps4X2yiDEPdxqTqJWw_i0ZzJf5pNeQ@mail.gmail.com>

What are some of the strategies for designing code to be unit tested?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120104/c01215fe/attachment.html>

From modulok at gmail.com  Thu Jan  5 08:07:31 2012
From: modulok at gmail.com (Modulok)
Date: Thu, 5 Jan 2012 00:07:31 -0700
Subject: [Tutor] Your thoughts on designing python code for unit testing?
In-Reply-To: <CABYizF+xiXurMtvnj3g3ps4X2yiDEPdxqTqJWw_i0ZzJf5pNeQ@mail.gmail.com>
References: <CABYizF+xiXurMtvnj3g3ps4X2yiDEPdxqTqJWw_i0ZzJf5pNeQ@mail.gmail.com>
Message-ID: <CAN2+EpbP99zQpRGn02KwmhBV3D9R7Y84nEDNm7QT5F05XOUHxw@mail.gmail.com>

In general, write the unit test *before* you write the code. This way your code
is "designed" to be unit tested by default. It also provides a better way to
verify that your implementation of a desired feature actually works as
intended.

For example, when I'm writing a new module I document it first. That is, I
write up a bunch of code samples on how to use the module. This gives me a feel
for what features I want and how I want the module to work. This is my sketch.
I use the Sphinx documentation generator for this, but it could be as
simple as a text document. After that I write a bunch of unit tests, which fail
because there is no module written yet. Then, I write the module code to make
each unit test pass, one by one.

If I want a new feature I document it, write the unit test, then implement it
until the unit test passes. If a feature is difficult to unit test, you
probably need to re-think how you're implementing it, or re-think the interface
itself. That said, this isn't always the case. With code that has to interact
with many external programs, unit testing certain features can be difficult, if
not impossible. Just try to get the best coverage you can.

Everyone has a little different process, but that's how I do it.
-Modulok-

On 1/4/12, brian arb <brianjamesarb at gmail.com> wrote:
> What are some of the strategies for designing code to be unit tested?
>

From jeanpierreda at gmail.com  Thu Jan  5 08:49:25 2012
From: jeanpierreda at gmail.com (Devin Jeanpierre)
Date: Thu, 5 Jan 2012 02:49:25 -0500
Subject: [Tutor] Your thoughts on designing python code for unit testing?
In-Reply-To: <CABYizF+xiXurMtvnj3g3ps4X2yiDEPdxqTqJWw_i0ZzJf5pNeQ@mail.gmail.com>
References: <CABYizF+xiXurMtvnj3g3ps4X2yiDEPdxqTqJWw_i0ZzJf5pNeQ@mail.gmail.com>
Message-ID: <CABicbJ+OSCdazTHGKM_nBjB7SF3Yt-ZFANA4CUfqCM24JdY3jw@mail.gmail.com>

I've found that bottom-up development favors testable code. That is,
rather than thinking of the problem to be solved, thinking in terms of
the tools (functions) one would use to solve the problem. These tools
can be written to be testable, and then it all builds up in this tower
of easily-testable and easy-to-use things until you have to actually
solve the problem at hand, at which point, ideally, it's just the
boring work of writing down the problem in terms of these tools.
(Digression: languages that let you do this earn the well-earned
reputation that source code can be like pseudocode).

It also makes the functions smaller and easier to read, which is a
nice bonus, especially during test failures -- lots of functions mean
your tests can be granular and say exactly where the problem is (more
or less), whereas being easy to read means less time searching for the
mistake.

-- Devin

On Wed, Jan 4, 2012 at 10:48 PM, brian arb <brianjamesarb at gmail.com> wrote:
>
> What are some of the?strategies?for designing code to be unit tested?
>
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From daedae11 at 126.com  Thu Jan  5 16:22:19 2012
From: daedae11 at 126.com (daedae11)
Date: Thu, 5 Jan 2012 23:22:19 +0800
Subject: [Tutor] question about a exercise
Message-ID: <2012010523221891579424@126.com>

The exercise is:

Write a function which has 3 parameters. First parameter is a char, second parameter is a integer, third parameter is a integer.
The function would create a file which have following requests:
1. the length of the file is in accordance with the third parameter.
2. the content of the file must be random generated.
3. the time first parameter occurred in the content must be in accordance with second parameter.

please give me some hints. It would be better if you give me the code.




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

From defensoft at gmail.com  Thu Jan  5 15:56:45 2012
From: defensoft at gmail.com (Nate Lastname)
Date: Thu, 5 Jan 2012 09:56:45 -0500
Subject: [Tutor] Game lag
Message-ID: <CABe2Fwp4UEGM9NWje2FFR2rXqCh=ZirNVSChH-D_Nh4rgMf6-Q@mail.gmail.com>

Hello all,

The attached zip file contains a file called 'cameramovement.py'.  As you
can see, this file is extremely laggy.  After searching through my code, I
can't find anything that is slowing it down.  Could someone help me out?
 It takes a while to load due to a large map.  This is not the problem.

Thanks,
The Defenestrator

P.S. Yes, I am new here.  Hello, all!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120105/aabf27de/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: cameraandplatformchar.zip
Type: application/zip
Size: 12092 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120105/aabf27de/attachment.zip>

From rhettnaxel at gmail.com  Thu Jan  5 16:29:17 2012
From: rhettnaxel at gmail.com (Alexander)
Date: Thu, 5 Jan 2012 10:29:17 -0500
Subject: [Tutor] question about a exercise
In-Reply-To: <2012010523221891579424@126.com>
References: <2012010523221891579424@126.com>
Message-ID: <CANS6qmBJf1YE+KS+dC8dBHW_07sYLwPif4Mhd7mjPiKmQPerXw@mail.gmail.com>

On Thu, Jan 5, 2012 at 10:22 AM, daedae11 <daedae11 at 126.com> wrote:

> **
> The exercise is:
>
> Write a function which has 3 parameters. First parameter is a char, second
> parameter is a integer, third parameter is a integer.
> The function would create a file which have following requests:
> 1. the length of the file is in accordance with the third parameter.
> 2. the content of the file must be random generated.
> 3. the time first parameter occurred in the content must be in accordance
> with second parameter.
>
> please give me some hints. It would be better if you give me the code.
>
> ------------------------------
> daedae11
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
> You're likely going to get patronized for asking for the code as if you're
asking for someone to do your homework problem for you.
-- 
Alexander
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120105/a461c034/attachment-0001.html>

From waynejwerner at gmail.com  Thu Jan  5 16:28:58 2012
From: waynejwerner at gmail.com (Wayne Werner)
Date: Thu, 5 Jan 2012 09:28:58 -0600
Subject: [Tutor] question about a exercise
In-Reply-To: <2012010523221891579424@126.com>
References: <2012010523221891579424@126.com>
Message-ID: <CAPM86NeFK0y4Z7VB3+GVn3ug1En_inQybPgUJNGrZO-9tky8QA@mail.gmail.com>

On Thu, Jan 5, 2012 at 9:22 AM, daedae11 <daedae11 at 126.com> wrote:

> **
> The exercise is:
>
> Write a function which has 3 parameters. First parameter is a char, second
> parameter is a integer, third parameter is a integer.
> The function would create a file which have following requests:
> 1. the length of the file is in accordance with the third parameter.
> 2. the content of the file must be random generated.
> 3. the time first parameter occurred in the content must be in accordance
> with second parameter.
>
> please give me some hints. It would be better if you give me the code.
>

It would be better if /you/ gave us the code that shows what you've tried.
Also, if we give you the solution(s) then you won't learn.

To accomplish this exercise you need a few skills:

1. Write a function that takes parameters - can you do this?
2. Create a file - can you do this?
3. Generate random text - can you do this?
4. Modify text (or generate slightly less-random text) - can you do this?

If you can do those four things then you should be able to easily
accomplish this task (that looks an awful lot like homework)

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120105/395c3951/attachment.html>

From rhettnaxel at gmail.com  Thu Jan  5 16:58:46 2012
From: rhettnaxel at gmail.com (Alexander)
Date: Thu, 5 Jan 2012 10:58:46 -0500
Subject: [Tutor] Using Python for a client interactive map application
Message-ID: <CANS6qmDZ4Vhnu_YiL5P1gM2XtyKOWRS9L87w5diD9aY=bxB5Cw@mail.gmail.com>

Dear friends,
I'm emailing regarding a general question about working with Python and a
web-browser based interactive map application. Over the summer I had asked
a similar question and heard some things about the Django framework, does
anybody have any other suggestions? For example there is a server with all
the info about a map, and from a browser a user will be able to view and
interact with the map at high speeds.
And please remember to reply to all.
Thanks,
-- 
Alexander
7D9C597B
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120105/a6017213/attachment.html>

From hugo.yoshi at gmail.com  Thu Jan  5 17:02:54 2012
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Thu, 5 Jan 2012 17:02:54 +0100
Subject: [Tutor] Game lag
In-Reply-To: <CABe2Fwp4UEGM9NWje2FFR2rXqCh=ZirNVSChH-D_Nh4rgMf6-Q@mail.gmail.com>
References: <CABe2Fwp4UEGM9NWje2FFR2rXqCh=ZirNVSChH-D_Nh4rgMf6-Q@mail.gmail.com>
Message-ID: <CAJmBOfmP80nXiF+fk84zsTfBu8c9Z+12=S4hCiXpodif9kZmgQ@mail.gmail.com>

On Thu, Jan 5, 2012 at 3:56 PM, Nate Lastname <defensoft at gmail.com> wrote:
> Hello all,
>
> The attached zip file contains a file called 'cameramovement.py'. ?As you
> can see, this file is extremely laggy. ?After searching through my code, I
> can't find anything that is slowing it down. ?Could someone help me out? ?It
> takes a while to load due to a large map. ?This is not the problem.
>
> Thanks,
> The Defenestrator
>
> P.S. Yes, I am new here. ?Hello, all!
>

1) although posting here is a good idea, you're gonna be better off
asking the pygame mailing list about this as well, they're the experts
2) that's a lot of code for me to read all in my spare time man, isn't
there any way you can simplify it or strip out unnecessary parts?
3) did you profile it? Do this! Now! rather than guess where your code
is slow, this will tell you exactly. Use cProfile:

http://docs.python.org/library/profile.html

HTH,
Hugo

From eire1130 at gmail.com  Thu Jan  5 17:04:19 2012
From: eire1130 at gmail.com (James Reynolds)
Date: Thu, 5 Jan 2012 11:04:19 -0500
Subject: [Tutor] Using Python for a client interactive map application
In-Reply-To: <CANS6qmDZ4Vhnu_YiL5P1gM2XtyKOWRS9L87w5diD9aY=bxB5Cw@mail.gmail.com>
References: <CANS6qmDZ4Vhnu_YiL5P1gM2XtyKOWRS9L87w5diD9aY=bxB5Cw@mail.gmail.com>
Message-ID: <CAE0jAbo5eGUki-SdC-8Ct0zLCmjfjfWbu-jAzAuEDpSkCS_gzQ@mail.gmail.com>

On Thu, Jan 5, 2012 at 10:58 AM, Alexander <rhettnaxel at gmail.com> wrote:

> Dear friends,
> I'm emailing regarding a general question about working with Python and a
> web-browser based interactive map application. Over the summer I had asked
> a similar question and heard some things about the Django framework, does
> anybody have any other suggestions? For example there is a server with all
> the info about a map, and from a browser a user will be able to view and
> interact with the map at high speeds.
> And please remember to reply to all.
> Thanks,
> --
> Alexander
> 7D9C597B
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

Django will (most likely) do what it is you want it to do, but you will
also need some javascript. For my current project, I'm using JQuery, but I
happen to know that Dojo has an interactive
map<http://download.dojotoolkit.org/release-1.7.1/dojo-release-1.7.1/dojox/geo/charting/tests/test_mapWithLegend.html>feature
in their toolset, so I would check that out dojo.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120105/5e0df867/attachment.html>

From defensoft at gmail.com  Thu Jan  5 17:08:46 2012
From: defensoft at gmail.com (Nate Lastname)
Date: Thu, 5 Jan 2012 11:08:46 -0500
Subject: [Tutor] Game lag
In-Reply-To: <CAJmBOfmP80nXiF+fk84zsTfBu8c9Z+12=S4hCiXpodif9kZmgQ@mail.gmail.com>
References: <CABe2Fwp4UEGM9NWje2FFR2rXqCh=ZirNVSChH-D_Nh4rgMf6-Q@mail.gmail.com>
	<CAJmBOfmP80nXiF+fk84zsTfBu8c9Z+12=S4hCiXpodif9kZmgQ@mail.gmail.com>
Message-ID: <CABe2Fwoy4rRy7dz=TOHdUyDWY3Z1q1Q4UN2-sHcAkCre4AhFSw@mail.gmail.com>

Thanks for the profilers - never had hear of 'em. Also, no, I cannot strip
out unnecessary parts, 'cuz I don't know what part is slowing it down.
 Thanks a lot, though Hugo.

On Thu, Jan 5, 2012 at 11:02 AM, Hugo Arts <hugo.yoshi at gmail.com> wrote:

> On Thu, Jan 5, 2012 at 3:56 PM, Nate Lastname <defensoft at gmail.com> wrote:
> > Hello all,
> >
> > The attached zip file contains a file called 'cameramovement.py'.  As you
> > can see, this file is extremely laggy.  After searching through my code,
> I
> > can't find anything that is slowing it down.  Could someone help me out?
>  It
> > takes a while to load due to a large map.  This is not the problem.
> >
> > Thanks,
> > The Defenestrator
> >
> > P.S. Yes, I am new here.  Hello, all!
> >
>
> 1) although posting here is a good idea, you're gonna be better off
> asking the pygame mailing list about this as well, they're the experts
> 2) that's a lot of code for me to read all in my spare time man, isn't
> there any way you can simplify it or strip out unnecessary parts?
> 3) did you profile it? Do this! Now! rather than guess where your code
> is slow, this will tell you exactly. Use cProfile:
>
> http://docs.python.org/library/profile.html
>
> HTH,
> Hugo
>



-- 
My Blog - Defenestration Coding

http://defenestrationcoding.wordpress.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120105/3ff65be9/attachment.html>

From hugo.yoshi at gmail.com  Thu Jan  5 17:23:41 2012
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Thu, 5 Jan 2012 17:23:41 +0100
Subject: [Tutor] Using Python for a client interactive map application
In-Reply-To: <CAE0jAbo5eGUki-SdC-8Ct0zLCmjfjfWbu-jAzAuEDpSkCS_gzQ@mail.gmail.com>
References: <CANS6qmDZ4Vhnu_YiL5P1gM2XtyKOWRS9L87w5diD9aY=bxB5Cw@mail.gmail.com>
	<CAE0jAbo5eGUki-SdC-8Ct0zLCmjfjfWbu-jAzAuEDpSkCS_gzQ@mail.gmail.com>
Message-ID: <CAJmBOfkqiVJewnG5njSUNbjf9y1=px9doth-d3X5DhxY89_aVQ@mail.gmail.com>

On Thu, Jan 5, 2012 at 5:04 PM, James Reynolds <eire1130 at gmail.com> wrote:
>
>
> On Thu, Jan 5, 2012 at 10:58 AM, Alexander <rhettnaxel at gmail.com> wrote:
>>
>> Dear friends,
>> I'm emailing regarding a general question about working with Python and a
>> web-browser based interactive map application. Over the summer I had asked a
>> similar question and heard some things about the Django framework, does
>> anybody have any other suggestions? For example there is a server with all
>> the info about a map, and from a browser a user will be able to view and
>> interact with the map at high speeds.
>> And please remember to reply to all.
>> Thanks,
>> --
>> Alexander
>> 7D9C597B
>>
>
>
> Django will (most likely) do what it is you want it to do, but you will also
> need some javascript. For my current project, I'm using JQuery, but I happen
> to know that Dojo has an interactive map feature in their toolset, so I
> would check that out dojo.
>

It sounds like the web server should do two jobs in this case:

1. deliver the javascript and assorted code that will draw the map,
along with a little html/css
2. respond to ajax requests from the javascript to deliver map data

any reasonable web framework will be able to do this just fine. Django
might even be a bit heavyweight for such a relatively simple task
(simple on the server side, that is). But there's nothing wrong with
using it anyway, if you're comfortable with it. Performance isn't
going to be an issue. You have a myriad of other options as well:
web2py, web.py, turbogears, pylons, cherrypy, you name it. Any of
these will do the job. If you already know one, I'd say pick that.
Otherwise, find one that looks simple and just go with it.

As for the format you'll be sending the map data in, I'd suggest json.
It's simple, easily read by humans and both python and javascript have
excellent tools for parsing and dumping (check out the json built-in
library for python).

HTH,
Hugo

From daedae11 at 126.com  Thu Jan  5 16:45:19 2012
From: daedae11 at 126.com (daedae11)
Date: Thu, 5 Jan 2012 23:45:19 +0800
Subject: [Tutor] question about gzip module
Message-ID: <2012010523451984550728@126.com>

Is there anyone who can give me an example of how to use the gzip module?
I have read the document, but there is no example in the document.
Thank you!!




daedae11
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120105/526896f0/attachment.html>

From lzantal at gmail.com  Thu Jan  5 17:55:50 2012
From: lzantal at gmail.com (lzantal)
Date: Thu, 5 Jan 2012 08:55:50 -0800
Subject: [Tutor] question about gzip module
In-Reply-To: <2012010523451984550728@126.com>
References: <2012010523451984550728@126.com>
Message-ID: <2951A733-2D80-42B1-8620-56F491D51322@gmail.com>

Good morning,

I learned it (and many other modules) from pymotw.
Here is a direct link to the gzip week.
http://www.doughellmann.com/PyMOTW/gzip/index.html#module-gzip

lzantal



On Jan 5, 2012, at 7:45 AM, daedae11 wrote:

> Is there anyone who can give me an example of how to use the gzip module?
> I have read the document, but there is no example in the document.
> Thank you!!
>  
> daedae11
> _______________________________________________
> 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/20120105/97996ced/attachment.html>

From wprins at gmail.com  Thu Jan  5 18:04:59 2012
From: wprins at gmail.com (Walter Prins)
Date: Thu, 5 Jan 2012 17:04:59 +0000
Subject: [Tutor] question about gzip module
In-Reply-To: <2012010523451984550728@126.com>
References: <2012010523451984550728@126.com>
Message-ID: <CANLXbfDLm9YuCJzaLFoPsD1SmXEB6Ni6+tVoOi_r4RB1Y4fvoA@mail.gmail.com>

Hi,

On 5 January 2012 15:45, daedae11 <daedae11 at 126.com> wrote:
> Is there anyone who can give me an example of how to use the gzip module?
> I have read the document, but there is no example in the document.

Which document are you referring to?   The Official Python
documentation does in fact contain examples also (See 12.2.1):
http://docs.python.org/library/gzip.html


(But +1 for PyMOTW as mentioned by Izantal.)

Walter

From alan.gauld at btinternet.com  Thu Jan  5 18:16:21 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 05 Jan 2012 17:16:21 +0000
Subject: [Tutor] Using Python for a client interactive map application
In-Reply-To: <CANS6qmDZ4Vhnu_YiL5P1gM2XtyKOWRS9L87w5diD9aY=bxB5Cw@mail.gmail.com>
References: <CANS6qmDZ4Vhnu_YiL5P1gM2XtyKOWRS9L87w5diD9aY=bxB5Cw@mail.gmail.com>
Message-ID: <je4lt5$3k9$1@dough.gmane.org>

On 05/01/12 15:58, Alexander wrote:

> framework, does anybody have any other suggestions? For example there is
> a server with all the info about a map, and from a browser a user will
> be able to view and interact with the map at high speeds.

High speeds? On a web application?
That usually means JavaScript and Ajax.

That's a non trivial application. It sounds a lot like Google maps?

Have you ever, just for fun, taken a look at the page source on a Google 
maps web page? You probably won't need all of the features of Google 
Maps but it might give you some idea of the scale of your challenge!

Now, accessing a map and displaying it and even making it mouse aware, 
that's a much easier task, but it may not be "high speed"...

HTH,

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


From rhettnaxel at gmail.com  Thu Jan  5 18:34:16 2012
From: rhettnaxel at gmail.com (Alexander)
Date: Thu, 5 Jan 2012 12:34:16 -0500
Subject: [Tutor] Using Python for a client interactive map application
In-Reply-To: <je4lt5$3k9$1@dough.gmane.org>
References: <CANS6qmDZ4Vhnu_YiL5P1gM2XtyKOWRS9L87w5diD9aY=bxB5Cw@mail.gmail.com>
	<je4lt5$3k9$1@dough.gmane.org>
Message-ID: <CANS6qmC+F4X+_e6CQU=v+5rq=T4AprUre3VSd4dkZVdZ8yA+EA@mail.gmail.com>

On Thu, Jan 5, 2012 at 12:16 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> On 05/01/12 15:58, Alexander wrote:
>
>  framework, does anybody have any other suggestions? For example there is
>> a server with all the info about a map, and from a browser a user will
>> be able to view and interact with the map at high speeds.
>>
>
> High speeds? On a web application?
> That usually means JavaScript and Ajax.
>
> That's a non trivial application. It sounds a lot like Google maps?
>
> Have you ever, just for fun, taken a look at the page source on a Google
> maps web page? You probably won't need all of the features of Google Maps
> but it might give you some idea of the scale of your challenge!
>
> Now, accessing a map and displaying it and even making it mouse aware,
> that's a much easier task, but it may not be "high speed"...
>
> HTH,
>
> --
> Alan G
> 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<http://mail.python.org/mailman/listinfo/tutor>
>

Yes I'm a little familiar with ajax. My freshman year I did a presentation
on ajax and google maps. Fortunately the scale of this project is far
easier and less complex than Google maps, which I find contain far more
data.

-- 
Alexander
7D9C597B
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120105/6f2c11e3/attachment.html>

From sierra_mtnview at sbcglobal.net  Thu Jan  5 18:38:47 2012
From: sierra_mtnview at sbcglobal.net (Wayne Watson)
Date: Thu, 05 Jan 2012 09:38:47 -0800
Subject: [Tutor] Return to my python26.dll & python.dll problems on bootup
Message-ID: <4F05E027.7010400@sbcglobal.net>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120105/a7146c34/attachment-0001.html>

From steve at pearwood.info  Thu Jan  5 19:25:38 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 06 Jan 2012 05:25:38 +1100
Subject: [Tutor] Return to my python26.dll & python.dll problems on
	bootup
In-Reply-To: <4F05E027.7010400@sbcglobal.net>
References: <4F05E027.7010400@sbcglobal.net>
Message-ID: <4F05EB22.5080808@pearwood.info>

Wayne Watson wrote:
>   I have two problems upon bootup of my Win7 PC, 64-bit.

Wayne, I sympathize with your problems, but they are Windows problems, not 
Python problems, and have absolutely nothing to do with learning to program 
Python. You are spamming this mailing list with off-topic questions about 
fixing your Windows system. This list is about learning Python programming, 
not "we'll fix any problem that has some vague connection to Python, no matter 
how slight". Have you tried asking for help on Windows-related forums or 
mailing lists?

It has been many years since I've used Windows regularly, but I can tell you 
this: you don't do yourself any favours by installing and uninstalling 
programs under Windows. I know it is less than helpful, but my advice is 
*never* install any program you aren't sure you will want to keep, because 
uninstalling always leaves traces of crud behind, eventually leading to 
exactly the sorts of problems you are experiencing.



-- 
Steven

From jsantos.lazer at gmail.com  Thu Jan  5 19:41:30 2012
From: jsantos.lazer at gmail.com (Joaquim Santos)
Date: Thu, 5 Jan 2012 18:41:30 +0000
Subject: [Tutor] Still the Python Challenge - Conclusion
Message-ID: <CAPC6Gu+YC_L7uy0LE9oi6KQic1K4nBMpigMUreJMFeoO=UHnmw@mail.gmail.com>

Hi List!

I just want to say thank you to all that helped me out!
I've now seen the errors I was doing and how to correct them. Now it
works as it should. I'll be sure to come back with more questions! And
one day help out someone else!

This is my script (I know that I only verify a small range but it
works for what I want for now...)

import string

def decrypt(cypheredText, shiftedCypherNumber):
    '''
This function will take two arguments. The first is the cyphered text,
the second
is the number of characters we need to shift the text so we can decrypt it.
This is a Caesar cypher.
    '''

    textTranslated = list()

    for letter in cypheredText:

        asciiValue = ord(letter)


        if asciiValue in range(97, 123):
            asciiValue += shiftedCypherNumber

            if asciiValue > 122:
                asciiValue -= 26

        newLetter = chr(asciiValue)


        textTranslated.append(newLetter)

    joinedText = ''.join(textTranslated)

    return joinedText


text = 'g fmnc wms bgblr rpylqjyrc gr zw fylb'

a = decrypt(text, 2)

print a

and this is the end result:

i hope you didnt translate it by hand
-- 

Joaquim Santos

http://js-vfx.com

linkedin

From robert.sjoblom at gmail.com  Fri Jan  6 00:00:48 2012
From: robert.sjoblom at gmail.com (Robert Sjoblom)
Date: Fri, 6 Jan 2012 00:00:48 +0100
Subject: [Tutor] Still the Python Challenge - Conclusion
In-Reply-To: <CAPC6Gu+YC_L7uy0LE9oi6KQic1K4nBMpigMUreJMFeoO=UHnmw@mail.gmail.com>
References: <CAPC6Gu+YC_L7uy0LE9oi6KQic1K4nBMpigMUreJMFeoO=UHnmw@mail.gmail.com>
Message-ID: <CAJKU7g3fOaLqwdULL-FrD3ZOCzx33xB0g2QsybWoFn6SLG4F9Q@mail.gmail.com>

On 5 January 2012 19:41, Joaquim Santos <jsantos.lazer at gmail.com> wrote:
> Hi List!
[...]
> This is my script (I know that I only verify a small range but it
> works for what I want for now...)
>
> import string
>
> def decrypt(cypheredText, shiftedCypherNumber):
> ? ?'''
> This function will take two arguments. The first is the cyphered text,
> the second
> is the number of characters we need to shift the text so we can decrypt it.
> This is a Caesar cypher.
> ? ?'''
>
> ? ?textTranslated = list()
>
> ? ?for letter in cypheredText:
>
> ? ? ? ?asciiValue = ord(letter)
>
>
> ? ? ? ?if asciiValue in range(97, 123):
> ? ? ? ? ? ?asciiValue += shiftedCypherNumber
>
> ? ? ? ? ? ?if asciiValue > 122:
> ? ? ? ? ? ? ? ?asciiValue -= 26
>
> ? ? ? ?newLetter = chr(asciiValue)
>
>
> ? ? ? ?textTranslated.append(newLetter)
>
> ? ?joinedText = ''.join(textTranslated)
>
> ? ?return joinedText
>
>
> text = 'g fmnc wms bgblr rpylqjyrc gr zw fylb'
>
> a = decrypt(text, 2)
>
> print a
>
> and this is the end result:

First of all, congratulations on solving it. Second, please don't
include the answer to any python challenges to this list as future
members or people searching for help with the same particular
challenge might not want to know the answer. Thirdly, I think you
should read PEP 8 - Style Guide for Python Code, but I'll quote the
absolutely most relevant part:
>Use blank lines in functions, sparingly, to indicate logical sections.
You don't need a blank line after every line of code; in fact, it
makes it harder to read. Where does one block end and another begin?

>PEP 257 describes good docstring conventions.  Note that most importantly, the """ that ends a multiline docstring should be on a line by itself, and preferably preceded by a blank line,

def decrypt(cypheredText, shiftedCypherNumber):
   '''This function will take two arguments. The first is the cyphered text,
the second is the number of characters we need to shift the text
so we can decrypt it. This is a Caesar cypher.

   '''
   textTranslated = list()
   for letter in cypheredText:
       asciiValue = ord(letter)
       if asciiValue in range(97, 123):
           asciiValue += shiftedCypherNumber
           #and so on

PEP 8 is really worth reading through: http://www.python.org/dev/peps/pep-0008/
there's also a link to PEP 257 in it. If you follow most of the
suggestions in PEP 8 it will be much easier to read your code, and
because of that easier to help you.

-- 
best regards,
Robert S.

From jsantos.lazer at gmail.com  Fri Jan  6 00:14:11 2012
From: jsantos.lazer at gmail.com (Joaquim Santos)
Date: Thu, 5 Jan 2012 23:14:11 +0000
Subject: [Tutor] Still the Python Challenge - Conclusion
In-Reply-To: <CAJKU7g3fOaLqwdULL-FrD3ZOCzx33xB0g2QsybWoFn6SLG4F9Q@mail.gmail.com>
References: <CAPC6Gu+YC_L7uy0LE9oi6KQic1K4nBMpigMUreJMFeoO=UHnmw@mail.gmail.com>
	<CAJKU7g3fOaLqwdULL-FrD3ZOCzx33xB0g2QsybWoFn6SLG4F9Q@mail.gmail.com>
Message-ID: <CAPC6GuKz+AGCMZg4bDbWALg0tZ5dU47SxKA4o7rfGVWbBhQSrg@mail.gmail.com>

Hi Robert!

Thanks for the heads up on the Style Guide. I'll read out the links
you pointed out to me.
About the script, result and Python Challenge, I  apologize,
however... in previous emails bigger pointers were given speaking
about using  'maketrans' to solve the challenge.
My way was a work around that I was trying to implement since day 1
and that can be (and maybe it will be) used as a base for a
(non-serious) deciphering program.

So, again, I'm sorry for presenting too much information, however more
important parts where said already and if people are willing to find
out by searching a list/web instead of trying out by themselves...
they are going to find it!

Cheers!

2012/1/5 Robert Sjoblom <robert.sjoblom at gmail.com>:
> On 5 January 2012 19:41, Joaquim Santos <jsantos.lazer at gmail.com> wrote:
>> Hi List!
> [...]
>> This is my script (I know that I only verify a small range but it
>> works for what I want for now...)
>>
>> import string
>>
>> def decrypt(cypheredText, shiftedCypherNumber):
>> ? ?'''
>> This function will take two arguments. The first is the cyphered text,
>> the second
>> is the number of characters we need to shift the text so we can decrypt it.
>> This is a Caesar cypher.
>> ? ?'''
>>
>> ? ?textTranslated = list()
>>
>> ? ?for letter in cypheredText:
>>
>> ? ? ? ?asciiValue = ord(letter)
>>
>>
>> ? ? ? ?if asciiValue in range(97, 123):
>> ? ? ? ? ? ?asciiValue += shiftedCypherNumber
>>
>> ? ? ? ? ? ?if asciiValue > 122:
>> ? ? ? ? ? ? ? ?asciiValue -= 26
>>
>> ? ? ? ?newLetter = chr(asciiValue)
>>
>>
>> ? ? ? ?textTranslated.append(newLetter)
>>
>> ? ?joinedText = ''.join(textTranslated)
>>
>> ? ?return joinedText
>>
>>
>> text = 'g fmnc wms bgblr rpylqjyrc gr zw fylb'
>>
>> a = decrypt(text, 2)
>>
>> print a
>>
>> and this is the end result:
>
> First of all, congratulations on solving it. Second, please don't
> include the answer to any python challenges to this list as future
> members or people searching for help with the same particular
> challenge might not want to know the answer. Thirdly, I think you
> should read PEP 8 - Style Guide for Python Code, but I'll quote the
> absolutely most relevant part:
>>Use blank lines in functions, sparingly, to indicate logical sections.
> You don't need a blank line after every line of code; in fact, it
> makes it harder to read. Where does one block end and another begin?
>
>>PEP 257 describes good docstring conventions. ?Note that most importantly, the """ that ends a multiline docstring should be on a line by itself, and preferably preceded by a blank line,
>
> def decrypt(cypheredText, shiftedCypherNumber):
> ? '''This function will take two arguments. The first is the cyphered text,
> the second is the number of characters we need to shift the text
> so we can decrypt it. This is a Caesar cypher.
>
> ? '''
> ? textTranslated = list()
> ? for letter in cypheredText:
> ? ? ? asciiValue = ord(letter)
> ? ? ? if asciiValue in range(97, 123):
> ? ? ? ? ? asciiValue += shiftedCypherNumber
> ? ? ? ? ? #and so on
>
> PEP 8 is really worth reading through: http://www.python.org/dev/peps/pep-0008/
> there's also a link to PEP 257 in it. If you follow most of the
> suggestions in PEP 8 it will be much easier to read your code, and
> because of that easier to help you.
>
> --
> best regards,
> Robert S.



-- 

Joaquim Santos

http://js-vfx.com

linkedin

From steve at pearwood.info  Fri Jan  6 01:22:07 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 06 Jan 2012 11:22:07 +1100
Subject: [Tutor] How to Capture a key being pressed?
In-Reply-To: <CAKXQjyW6pDCdpd1L1XqvFQSxM67266-x6Un231BYcGHrMtVdOQ@mail.gmail.com>
References: <CAKXQjyW6pDCdpd1L1XqvFQSxM67266-x6Un231BYcGHrMtVdOQ@mail.gmail.com>
Message-ID: <4F063EAF.9040506@pearwood.info>

brandon w wrote:
> How do I capture a key like the <Space> bar or the <Enter> key? 

http://code.activestate.com/recipes/577977-get-single-keypress/



-- 
Steven

From lie.1296 at gmail.com  Fri Jan  6 19:29:10 2012
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sat, 07 Jan 2012 05:29:10 +1100
Subject: [Tutor] Using Python for a client interactive map application
In-Reply-To: <je4lt5$3k9$1@dough.gmane.org>
References: <CANS6qmDZ4Vhnu_YiL5P1gM2XtyKOWRS9L87w5diD9aY=bxB5Cw@mail.gmail.com>
	<je4lt5$3k9$1@dough.gmane.org>
Message-ID: <je7eho$hd0$1@dough.gmane.org>

On 01/06/2012 04:16 AM, Alan Gauld wrote:
> That's a non trivial application. It sounds a lot like Google maps?

If by map you meant real world maps, this task becomes pretty much 
trivial. It is fairly easy to embed Google Map in your own web app, and 
their API provides a lot for almost anything you would need to do.

Although Google Maps are often used for boring everyday tasks like 
ordering taxi, reporting potholes, finding public toilets, etc, etc 
http://mashable.com/2009/01/08/google-maps-mashups-tools/

These are also some examples of the quirkiest things you could do with 
Google Maps:

- http://geoquake.jp/en/webgame/DrivingSimulatorPerspective/
- http://www.class3outbreak.com/
- 
http://www.thekremercollection.com/art/artists/Abraham-Bloemaert/A-cottage-with-peasants-milking-goats/


From garland.binns at gmail.com  Fri Jan  6 21:05:02 2012
From: garland.binns at gmail.com (Garland W. Binns)
Date: Fri, 6 Jan 2012 14:05:02 -0600
Subject: [Tutor] Making a Computer Guess My Number
Message-ID: <CA+sODKwid_AnD=YbiBiD9BbMBKqd4b2gm9CqOr48yXFbgDb00A@mail.gmail.com>

Hello, I have been experimenting with trying to rewrite the following
script so that a computer tries to guess a number I'm thinking of:
https://gist.github.com/1572067

I was thinking that basically I need to create a while loop, and somehow
redefine the randrange depending on whether or not I provide raw input
saying that the guess is higher or lower.

 Can anyone offer any suggestions?

--
Garland W. Binns
Facebook <https://www.facebook.com/garland.binns> /
LinkedIn<http://linkedin.com/in/garlandbinns>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120106/347e243c/attachment.html>

From d at davea.name  Fri Jan  6 21:21:58 2012
From: d at davea.name (Dave Angel)
Date: Fri, 06 Jan 2012 15:21:58 -0500
Subject: [Tutor] Making a Computer Guess My Number
In-Reply-To: <CA+sODKwid_AnD=YbiBiD9BbMBKqd4b2gm9CqOr48yXFbgDb00A@mail.gmail.com>
References: <CA+sODKwid_AnD=YbiBiD9BbMBKqd4b2gm9CqOr48yXFbgDb00A@mail.gmail.com>
Message-ID: <4F0757E6.6000801@davea.name>

On 01/06/2012 03:05 PM, Garland W. Binns wrote:
> Hello, I have been experimenting with trying to rewrite the following
> script so that a computer tries to guess a number I'm thinking of:
> https://gist.github.com/1572067
>
> I was thinking that basically I need to create a while loop, and somehow
> redefine the randrange depending on whether or not I provide raw input
> saying that the guess is higher or lower.
>
>   Can anyone offer any suggestions?
>
> -
Sure.  Start from scratch.

Seriously, the program you're desiring has little to do with the one you 
already wrote, other than probably using print and raw_input.  The 
optimal answer doesn't even need any random calls in it.

Are you familiar with the concept of binary search?  That's what you 
should implement.

Take a crack at it, and see what you come up with.

Hint:  think of a way to express the thinking part (the alogorithm) as a 
function, and write that first.  Then you just write something that 
controls its calls to the function based on user input.

-- 

DaveA


From cfuller084 at thinkingplanet.net  Sat Jan  7 04:24:40 2012
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Fri, 6 Jan 2012 21:24:40 -0600
Subject: [Tutor] Subclassing Exceptions
Message-ID: <201201062124.41384.cfuller084@thinkingplanet.net>

I had an interesting experience today.

Python 2.7.1 (r271:86832, Nov 28 2010, 19:31:37) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(Exception):
...  def __init__(self, a,b,c):
...   self.args = (a,b,c)
... 
>>> raise Foo(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.Foo: (1, 2, 3)
>>> class Foo(SyntaxError):
...  def __init__(self, a,b,c):
...   self.args = (a,b,c)
... 
>>> raise Foo(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.Foo: None


Inheriting from SyntaxError doesn't work!  When I create a new exception, I 
generally subclass from the built-in exception it most resembles, in case 
there was some reason to also catch it via an ancestor.  But I'm not sure if 
that is really all that useful an idea in practice.  How do you folk do it?

By the way, inheriting from StandardError, the direct ancestor of  
SyntaxError, works as expected, and its parent is Exception.

Cheers

From daedae11 at 126.com  Sat Jan  7 04:57:06 2012
From: daedae11 at 126.com (daedae11)
Date: Sat, 7 Jan 2012 11:57:06 +0800
Subject: [Tutor] How to invoke different member-function according to
	different object?
Message-ID: <2012010711570599909815@126.com>

I was asked to write a program to move files between ZIP(.zip) and TAR/GZIP(.tgz/.tar.gz) or TAR/BZIP2(.tbz/.tar.bz2) archive. 

my code is:


import zipfile;
import tarfile;
import os;
from os import path ;

def showAllFiles(fileObj):
    if fileObj.filename.endswith("zip"):
        if isinstance(fileObj, zipfile.ZipFile):
            print "j"*20;
        for name in fileObj.namelist():
            print name;
    else:
        for name in fileObj.getnames():
            print name; 

def moveFile(srcObj, dstObj):
    fileName = raw_input("input the name of the file to move: ");    
    srcObj.extract(fileName);
    if isinstance(dstObj, zipfile.ZipFile):
        dstObj.write(fileName);
    else:
        dstObj.addfile(tarfile.TarInfo(fileName));
    os.remove(fileName);    
    
def main():
    intro = """
enter a choice
(M)ove file from source file to destinatiom file
(S)how all the files in source file
(Q)uit
your choice is: """    
    srcFile = raw_input("input the source file name: ");
    dstFile = raw_input("input the destination file name: ");
    while True:
        with ( zipfile.ZipFile(srcFile, "r") if srcFile.endswith("zip") else tarfile.open(srcFile, "r"+":"+path.splitext(srcFile)[1][1:]) ) as srcObj, \
        ( zipfile.ZipFile(dstFile, "r") if
           dstFile.endswith("zip") else
            tarfile.open(dstFile, "w"+":"+path.splitext(dstFile)[1][1:]) ) as dstObj:        
                choice = raw_input(intro)[0].lower();
                if choice == "s":
                    showAllFiles(srcObj);
                elif choice == "m":
                    moveFile(srcObj, dstObj);
                elif choice == "q":
                    break;
                else:
                    print "invalid command!"

if __name__ == '__main__':
    main();

But there are some problems.
1. It could extract file successfully, but can't add files to .tar.gz file.
2. I think it's a little tedious, but I don't know how to improve it.

Please  give me some help , thank you!




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

From jeanpierreda at gmail.com  Sat Jan  7 05:42:49 2012
From: jeanpierreda at gmail.com (Devin Jeanpierre)
Date: Fri, 6 Jan 2012 23:42:49 -0500
Subject: [Tutor] Subclassing Exceptions
In-Reply-To: <201201062124.41384.cfuller084@thinkingplanet.net>
References: <201201062124.41384.cfuller084@thinkingplanet.net>
Message-ID: <CABicbJLPCPyOfd815KmtOrFQdPoCn0Gptgz_cQ1_3=cvV7WOsQ@mail.gmail.com>

> Inheriting from SyntaxError doesn't work!  When I create a new exception, I
> generally subclass from the built-in exception it most resembles, in case
> there was some reason to also catch it via an ancestor.  But I'm not sure if
> that is really all that useful an idea in practice.  How do you folk do it?

If somebody wanted to catch a ValueError, would they also mean to
catch my error? (The same with SyntaxError and so on). Probably not.
If they would, then I raise the relevant exception. It is very
possible to accidentally catch the wrong thing if you put too much in
a try block, and I don't like making that any easier.

-- Devin

On Fri, Jan 6, 2012 at 10:24 PM, Chris Fuller
<cfuller084 at thinkingplanet.net> wrote:
> I had an interesting experience today.
>
> Python 2.7.1 (r271:86832, Nov 28 2010, 19:31:37)
> [GCC 4.4.5] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> class Foo(Exception):
> ... ?def __init__(self, a,b,c):
> ... ? self.args = (a,b,c)
> ...
>>>> raise Foo(1,2,3)
> Traceback (most recent call last):
> ?File "<stdin>", line 1, in <module>
> __main__.Foo: (1, 2, 3)
>>>> class Foo(SyntaxError):
> ... ?def __init__(self, a,b,c):
> ... ? self.args = (a,b,c)
> ...
>>>> raise Foo(1,2,3)
> Traceback (most recent call last):
> ?File "<stdin>", line 1, in <module>
> __main__.Foo: None
>
>
> Inheriting from SyntaxError doesn't work!  When I create a new exception, I
> generally subclass from the built-in exception it most resembles, in case
> there was some reason to also catch it via an ancestor.  But I'm not sure if
> that is really all that useful an idea in practice.  How do you folk do it?
>
> By the way, inheriting from StandardError, the direct ancestor of
> SyntaxError, works as expected, and its parent is Exception.
>
> Cheers
> _______________________________________________
> 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 Jan  7 05:56:32 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 07 Jan 2012 15:56:32 +1100
Subject: [Tutor] Subclassing Exceptions
In-Reply-To: <201201062124.41384.cfuller084@thinkingplanet.net>
References: <201201062124.41384.cfuller084@thinkingplanet.net>
Message-ID: <4F07D080.8080600@pearwood.info>

Chris Fuller wrote:

>>>> class Foo(SyntaxError):
> ...  def __init__(self, a,b,c):
> ...   self.args = (a,b,c)
> ... 
>>>> raise Foo(1,2,3)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> __main__.Foo: None
> 
> 
> Inheriting from SyntaxError doesn't work!  When I create a new exception, I 
> generally subclass from the built-in exception it most resembles, in case 
> there was some reason to also catch it via an ancestor.  But I'm not sure if 
> that is really all that useful an idea in practice.  How do you folk do it?

What do you mean, "doesn't work"? It looks like it works to me. You get a Foo 
exception, exactly as expected. The error message isn't what you expect, 
because you're making unwarranted assumptions about SyntaxError and how it works.

In general, when you override a method, you take full responsibility to 
perform everything that the superclass method was supposed to do. In this 
case, you fail to assign to msg as well as args. It is safer to overload a 
message rather than override it:

 >>> class Spam(SyntaxError):
...     def __init__(self, *args):
...             if args:
...                     args  = ("I pity the fool who made a mistake",) + args[1:]
...             super(Spam, self).__init__(*args)
...
 >>>
 >>> raise Spam('you made a mistake', 1, 2)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
__main__.Spam: I pity the fool who made a mistake



Unfortunately, there's no real consistency in what arguments exceptions are 
expected to take. The best thing is to read the docs, if they have any, or use 
introspection and trial and error to work out what they do.

 >>> try:
...     raise SyntaxError("you made a mistake")
... except SyntaxError, err:
...     pass
...
 >>> err.msg
'you made a mistake'


See dir(err) for more; you can use help(SyntaxError) but unfortunately it 
isn't very useful.


You probably shouldn't inherit from SyntaxError, since it represents syntax 
errors in the Python code being interpreted or compiled. Any syntax error in 
your own data structures should be independent of SyntaxError.




-- 
Steven




From steve at pearwood.info  Sat Jan  7 06:06:06 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 07 Jan 2012 16:06:06 +1100
Subject: [Tutor] Subclassing Exceptions
In-Reply-To: <CABicbJLPCPyOfd815KmtOrFQdPoCn0Gptgz_cQ1_3=cvV7WOsQ@mail.gmail.com>
References: <201201062124.41384.cfuller084@thinkingplanet.net>
	<CABicbJLPCPyOfd815KmtOrFQdPoCn0Gptgz_cQ1_3=cvV7WOsQ@mail.gmail.com>
Message-ID: <4F07D2BE.7090106@pearwood.info>

Devin Jeanpierre wrote:
>> Inheriting from SyntaxError doesn't work!  When I create a new exception, I
>> generally subclass from the built-in exception it most resembles, in case
>> there was some reason to also catch it via an ancestor.  But I'm not sure if
>> that is really all that useful an idea in practice.  How do you folk do it?
> 
> If somebody wanted to catch a ValueError, would they also mean to
> catch my error? (The same with SyntaxError and so on). Probably not.

If your error represents a value error, then yes they would.

But in that case, why should I subclass ValueError instead of just using 
ValueError itself? Writing my own exceptions is only useful if I intend to 
give the caller the *choice* of either treating my exception the same or 
different from ValueError: that is, if my error is a more specific kind of 
ValueError. If it is not a specific kind of value error, then just use the 
generic built-in ValueError exception instead.


try:
     x = some_function()
except MyValueError:
     # treat my errors specially
except ValueError:
     # any other kind of ValueError caught here

vs.

try:
     x = some_function()
except ValueError:
     # any kind of ValueError caught here, including MyValueError


The same goes for all exception types, although in practice I find that I 
generally only subclass ValueError.



-- 
Steven

From steve at pearwood.info  Sat Jan  7 06:15:43 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 07 Jan 2012 16:15:43 +1100
Subject: [Tutor] How to invoke different member-function according to
 different object?
In-Reply-To: <2012010711570599909815@126.com>
References: <2012010711570599909815@126.com>
Message-ID: <4F07D4FF.6040701@pearwood.info>

daedae11 wrote:

> 2. I think it's a little tedious, but I don't know how to improve it.


Welcome to programming!

In the school books and example code, you see a nice, clean, fifteen line 
function and think that programming is easy.

Then you try to write the program, and you start of with 15 lines of code. 
Then you add error handling, and you end up with 50 lines. Then you add a user 
interface, and you have 130 lines. Then the user interface needs error 
handling, and you have 250 lines of code. Then you try to improve the 
presentation of the output, and you have 600 lines of code. Add error handling 
to that, and a test suite, and before you know it, your 15 line function is 
buried in the middle of a 3,000 line application.

Real programs always end up much bigger and more complicated and tedious than 
the way you think they should be.



-- 
Steven

From __peter__ at web.de  Sat Jan  7 13:00:24 2012
From: __peter__ at web.de (Peter Otten)
Date: Sat, 07 Jan 2012 13:00:24 +0100
Subject: [Tutor] How to invoke different member-function according to
	different object?
References: <2012010711570599909815@126.com>
Message-ID: <je9c4l$cu5$1@dough.gmane.org>

daedae11 wrote:

> I was asked to write a program to move files between ZIP(.zip) and
> TAR/GZIP(.tgz/.tar.gz) or TAR/BZIP2(.tbz/.tar.bz2) archive.
> 
> my code is:
> 
> 
> import zipfile;
> import tarfile;
> import os;
> from os import path ;
> 
> def showAllFiles(fileObj):
>     if fileObj.filename.endswith("zip"):
>         if isinstance(fileObj, zipfile.ZipFile):
>             print "j"*20;
>         for name in fileObj.namelist():
>             print name;
>     else:
>         for name in fileObj.getnames():
>             print name;
> 
> def moveFile(srcObj, dstObj):
>     fileName = raw_input("input the name of the file to move: ");
>     srcObj.extract(fileName);
>     if isinstance(dstObj, zipfile.ZipFile):
>         dstObj.write(fileName);
>     else:
>         dstObj.addfile(tarfile.TarInfo(fileName));
>     os.remove(fileName);
>     
> def main():
>     intro = """
> enter a choice
> (M)ove file from source file to destinatiom file
> (S)how all the files in source file
> (Q)uit
> your choice is: """
>     srcFile = raw_input("input the source file name: ");
>     dstFile = raw_input("input the destination file name: ");
>     while True:
>         with ( zipfile.ZipFile(srcFile, "r") if srcFile.endswith("zip")
>         else tarfile.open(srcFile, "r"+":"+path.splitext(srcFile)[1][1:])
>         ) as srcObj, \ ( zipfile.ZipFile(dstFile, "r") if
>            dstFile.endswith("zip") else
>             tarfile.open(dstFile, "w"+":"+path.splitext(dstFile)[1][1:]) )
>             as dstObj:
>                 choice = raw_input(intro)[0].lower();
>                 if choice == "s":
>                     showAllFiles(srcObj);
>                 elif choice == "m":
>                     moveFile(srcObj, dstObj);
>                 elif choice == "q":
>                     break;
>                 else:
>                     print "invalid command!"
> 
> if __name__ == '__main__':
>     main();
> 
> But there are some problems.
> 1. It could extract file successfully, but can't add files to .tar.gz
> file. 2. I think it's a little tedious, but I don't know how to improve
> it.
> 
> Please  give me some help , thank you!

First, but least: don't pollute your code with trailing semicola.
Second: what Steven says, plus it will always take you longer to implement a 
script than you initially think. I ran into that for the umpteenth time when 
trying to reorganize your script.

Now to your code:
- Try to separate the user interface (aka raw_input()) from the other 
functionality of your script. moveFile() will be easier to test when you  
pass the filename as an argument rather than asking the user for it. 

- Don't overuse inlined if-else expressions. A separate

if complex condition:
   var = ...
else:
   var = ...

is easier to read -- and easier to extend with another elif.

- If you have a lot of if-else switches consider classes

# wrong
animal = dog_or_duck()
if its_a_dog(animal):
   bark()
elif its_a_duck(animal):
   quack()

# right
animal = dog_or_duck()
animal.make_some_noise()

In your case there already are classes, but with incompatible interfaces. 
You can solve that by subclassing or making wrapper classes.

Another approach that addresses the same problem is table-driven:

def quack(): print "quack"
def bark(): print "wuff"
lookup_noise = {
    Dog: bark,
    Duck: quack,
}
animal = dog_or_duck()
lookup_noise[animal.__class__]()

In my rewritten version of your script I use both approaches. It is still 
incomplete and has already become almost too long to post. It is probably a 
bit too complex for a beginner, too, but the idea is simple and if you have 
questions I'm willing to answer. 

Basically there is a class for every archive type which has to implement an 
open(name) method which has to return a file-like object and an add(name, 
file) which has to add a file-like object as name to the archive.
You can ask if a certain archive class can deal with a file with e. g.

ZipArchive.can_handle(filename)

The script features an adhoc test that you can invoke with

python scriptname.py --test

Look into http://docs.python.org/library/unittest.html if you are serious 
about testing. I think you should be ;)

import os
import shutil
import sys
import tarfile
import zipfile

def _not_implemented(obj, methodname):
    typename = obj.__class__.__name__
    print >> sys.stderr, "{}.{}() not implemented".format(typename, 
methodname)

class Archive(object):
    @classmethod
    def can_handle(class_, filename):
        return filename.lower().endswith(class_.suffixes)

    def __init__(self, filename, mode):
        if mode not in ("r", "w"):
            raise ValueError("Mode {} not understood".format(mode))
        self.filename = filename
        self.mode = mode
        self._archive = self._open_archive()
    def getnames(self):
        return self._archive.getnames()
    def __enter__(self):
        return self
    def __exit__(self, *args):
        self._archive.close()

    def _open_archive(self):
        _not_implemented(self, "_open")
    def add(self, name, srcfile):
        _not_implemented(self, "add")
    def open(self, name):
        _not_implemented(self, "extract")

class ZipArchive(Archive):
    suffixes = (".zip",)
    def _open_archive(self):
        return zipfile.ZipFile(self.filename, self.mode)
    def getnames(self):
        return self._archive.namelist()
    def open(self, name):
        return self._archive.open(name)

class TarArchive(Archive):
    suffixes = (".tar",)
    def _open_archive(self):
        return tarfile.open(self.filename, self.mode)
    def add(self, name, srcfile):
        tmpname = "tmp.xxx" # TODO use tempfile module
        with open(tmpname, "wb") as dstfile:
            shutil.copyfileobj(srcfile, dstfile)
        self._archive.add(tmpname, name)
        os.remove(tmpname)

class TgzArchive(TarArchive):
    suffixes = (".tar.gz", ".tgz")
    def _open_archive(self):
        return tarfile.open(self.filename, self.mode + ":gz")

lookup = [
    ZipArchive,
    TarArchive,
    TgzArchive,
]

def move_file(src, dst, filename):
    dst.add(filename, src.open(filename))

def open_archive(filename, mode):
    for Archive in lookup:
        if Archive.can_handle(filename):
            return Archive(filename, mode)
    raise ValueError("Archive type of {!r} not understood".format(filename))

def show_all_files(archive):
    for name in archive.getnames():
        print name

def main():
    if "--test" in sys.argv:
        with zipfile.ZipFile("one.zip", "w") as dst:
            for data in "alpha beta gamma".split():
                dst.writestr(data + ".txt", data)
        with open_archive("one.zip", "r") as src:
            with open_archive("two.tar", "w") as dst:
                move_file(src, dst, "alpha.txt")
            with open_archive("three.tar.gz", "w") as dst:
                move_file(src, dst, "beta.txt")
                move_file(src, dst, "gamma.txt")
        with tarfile.open("two.tar") as src:
            assert src.getnames() == ["alpha.txt"]
        with tarfile.open("three.tar.gz") as src:
            assert src.getnames() == ["beta.txt", "gamma.txt"]
        # TODO: check contents
        return

    intro = """
enter a choice
(M)ove file from source file to destinatiom file
(S)how all the files in source file
(Q)uit
your choice is: """
    srcname = raw_input("input the source file name: ")
    dstname = raw_input("input the destination file name: ")
    with open_archive(srcname, "r") as src:
        while True:
            choice = raw_input(intro).strip().lower()
            if choice == "s":
                show_all_files(src)
            elif choice == "m":
                filename = raw_input("input the name of the file to move: ")
                with open_archive(dstname, "w") as dst:
                    move_file(src, dst, filename)
            elif choice == "q":
                break
            else:
                print "invalid command ({!r})!" % choice

if __name__ == '__main__':
    main()


From mehgcap at gmail.com  Sat Jan  7 18:53:22 2012
From: mehgcap at gmail.com (Alex Hall)
Date: Sat, 7 Jan 2012 12:53:22 -0500
Subject: [Tutor] making a custom file parser?
Message-ID: <CAF=P20UoF7Fn5W+qnpO1rASQVJbYKDQ0sBC9-rpWm3Hvhit7Tg@mail.gmail.com>

Hello all,
I have a file with xml-ish code in it, the definitions for units in a
real-time strategy game. I say xml-ish because the tags are like xml,
but no quotes are used and most tags do not have to end. Also,
comments in this file are prefaced by an apostrophe, and there is no
multi-line commenting syntax. For example:

<unit>
<number=1>
<name=my unit>
<canMove=True>
<canCarry=unit2, unit3, unit4>
'this line is a comment
</unit>

The game is not mine, but I would like to put together a python
interface to more easily manage custom units for it. To do that, I
have to be able to parse these files, but elementtree does not seem to
like them very much. I imagine it is due to the lack of quotes, the
non-standard commenting method, and the lack of closing tags. I think
my only recourse here is to create my own parser and tell elementtree
to use that. The docs say this is possible, but they also seem to
indicate that the parser has to already exist in the elementtree
package and there is no mention of making one's own method for
parsing. Even if this were possible, though, I am not sure how to go
about it. I can of course strip comments, but that is as far as I have
gotten.

Bottom line: can I create a method and tell elementtree to parse using
it, and what would such a function look like (generally) if I can?
Thanks!

-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From cfuller084 at thinkingplanet.net  Sat Jan  7 20:01:21 2012
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Sat, 7 Jan 2012 13:01:21 -0600
Subject: [Tutor] making a custom file parser?
In-Reply-To: <CAF=P20UoF7Fn5W+qnpO1rASQVJbYKDQ0sBC9-rpWm3Hvhit7Tg@mail.gmail.com>
References: <CAF=P20UoF7Fn5W+qnpO1rASQVJbYKDQ0sBC9-rpWm3Hvhit7Tg@mail.gmail.com>
Message-ID: <201201071301.21959.cfuller084@thinkingplanet.net>


If it's unambiguous as to which tags are closed and which are not, then it's 
pretty easy to preprocess the file into valid XML.  Scan for the naughty bits 
(single quotes) and insert escape characters, replace with something else, 
etc., then scan for the unterminated tags and throw in a "/" at the end.

Anyhow, if there's no tree structure, or its only one level deep, using 
ElementTree is probably overkill and just gives you lots of leaking 
abstractions to plug for little benefit.  Why not just scan the file directly?

Cheers

On Saturday 07 January 2012, Alex Hall wrote:
> Hello all,
> I have a file with xml-ish code in it, the definitions for units in a
> real-time strategy game. I say xml-ish because the tags are like xml,
> but no quotes are used and most tags do not have to end. Also,
> comments in this file are prefaced by an apostrophe, and there is no
> multi-line commenting syntax. For example:
> 
> <unit>
> <number=1>
> <name=my unit>
> <canMove=True>
> <canCarry=unit2, unit3, unit4>
> 'this line is a comment
> </unit>
> 
> The game is not mine, but I would like to put together a python
> interface to more easily manage custom units for it. To do that, I
> have to be able to parse these files, but elementtree does not seem to
> like them very much. I imagine it is due to the lack of quotes, the
> non-standard commenting method, and the lack of closing tags. I think
> my only recourse here is to create my own parser and tell elementtree
> to use that. The docs say this is possible, but they also seem to
> indicate that the parser has to already exist in the elementtree
> package and there is no mention of making one's own method for
> parsing. Even if this were possible, though, I am not sure how to go
> about it. I can of course strip comments, but that is as far as I have
> gotten.
> 
> Bottom line: can I create a method and tell elementtree to parse using
> it, and what would such a function look like (generally) if I can?
> Thanks!


From mehgcap at gmail.com  Sat Jan  7 20:22:54 2012
From: mehgcap at gmail.com (Alex Hall)
Date: Sat, 7 Jan 2012 14:22:54 -0500
Subject: [Tutor] making a custom file parser?
In-Reply-To: <201201071301.21959.cfuller084@thinkingplanet.net>
References: <CAF=P20UoF7Fn5W+qnpO1rASQVJbYKDQ0sBC9-rpWm3Hvhit7Tg@mail.gmail.com>
	<201201071301.21959.cfuller084@thinkingplanet.net>
Message-ID: <CAF=P20XjYM1C0XycnWKFHwg8SRgPNJ8k8Eduk=SAj9NCazYbVA@mail.gmail.com>

I had planned to parse myself, but am not sure how to go about it. I
assume regular expressions, but I couldn't even find the amount of
units in the file by using:
unitReg=re.compile(r"\<unit\>(*)\</unit\>")
unitCount=unitReg.search(fileContents)
print "number of units: "+unitCount.len(groups())

I just get an exception that "None type object has no attribute
groups", meaning that the search was unsuccessful. What I was hoping
to do was to grab everything between the opening and closing unit
tags, then read it one at a time and parse further. There is a tag
inside a unit tag called AttackTable which also terminates, so I would
need to pull that out and work with it separately. I probably just
have misunderstood how regular expressions and groups work...


On 1/7/12, Chris Fuller <cfuller084 at thinkingplanet.net> wrote:
>
> If it's unambiguous as to which tags are closed and which are not, then it's
> pretty easy to preprocess the file into valid XML.  Scan for the naughty
> bits
> (single quotes) and insert escape characters, replace with something else,
> etc., then scan for the unterminated tags and throw in a "/" at the end.
>
> Anyhow, if there's no tree structure, or its only one level deep, using
> ElementTree is probably overkill and just gives you lots of leaking
> abstractions to plug for little benefit.  Why not just scan the file
> directly?
>
> Cheers
>
> On Saturday 07 January 2012, Alex Hall wrote:
>> Hello all,
>> I have a file with xml-ish code in it, the definitions for units in a
>> real-time strategy game. I say xml-ish because the tags are like xml,
>> but no quotes are used and most tags do not have to end. Also,
>> comments in this file are prefaced by an apostrophe, and there is no
>> multi-line commenting syntax. For example:
>>
>> <unit>
>> <number=1>
>> <name=my unit>
>> <canMove=True>
>> <canCarry=unit2, unit3, unit4>
>> 'this line is a comment
>> </unit>
>>
>> The game is not mine, but I would like to put together a python
>> interface to more easily manage custom units for it. To do that, I
>> have to be able to parse these files, but elementtree does not seem to
>> like them very much. I imagine it is due to the lack of quotes, the
>> non-standard commenting method, and the lack of closing tags. I think
>> my only recourse here is to create my own parser and tell elementtree
>> to use that. The docs say this is possible, but they also seem to
>> indicate that the parser has to already exist in the elementtree
>> package and there is no mention of making one's own method for
>> parsing. Even if this were possible, though, I am not sure how to go
>> about it. I can of course strip comments, but that is as far as I have
>> gotten.
>>
>> Bottom line: can I create a method and tell elementtree to parse using
>> it, and what would such a function look like (generally) if I can?
>> Thanks!
>
>


-- 
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  Sat Jan  7 21:15:15 2012
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sat, 7 Jan 2012 21:15:15 +0100
Subject: [Tutor] making a custom file parser?
In-Reply-To: <CAF=P20XjYM1C0XycnWKFHwg8SRgPNJ8k8Eduk=SAj9NCazYbVA@mail.gmail.com>
References: <CAF=P20UoF7Fn5W+qnpO1rASQVJbYKDQ0sBC9-rpWm3Hvhit7Tg@mail.gmail.com>
	<201201071301.21959.cfuller084@thinkingplanet.net>
	<CAF=P20XjYM1C0XycnWKFHwg8SRgPNJ8k8Eduk=SAj9NCazYbVA@mail.gmail.com>
Message-ID: <CAJmBOf=9dcrR=iw3-04vUtH0ND4Smf2H92vpTvks8mvPkDQxkw@mail.gmail.com>

On Sat, Jan 7, 2012 at 8:22 PM, Alex Hall <mehgcap at gmail.com> wrote:
> I had planned to parse myself, but am not sure how to go about it. I
> assume regular expressions, but I couldn't even find the amount of
> units in the file by using:
> unitReg=re.compile(r"\<unit\>(*)\</unit\>")
> unitCount=unitReg.search(fileContents)
> print "number of units: "+unitCount.len(groups())
>
> I just get an exception that "None type object has no attribute
> groups", meaning that the search was unsuccessful. What I was hoping
> to do was to grab everything between the opening and closing unit
> tags, then read it one at a time and parse further. There is a tag
> inside a unit tag called AttackTable which also terminates, so I would
> need to pull that out and work with it separately. I probably just
> have misunderstood how regular expressions and groups work...
>

Parsing XML with regular expressions is generally very bad idea. In
the general case, it's actually impossible. XML is not what is called
a regular language, and therefore cannot be parsed with regular
expressions. You can use regular expressions to grab a limited amount
of data from a limited set of XML files, but this is dangerous, hard,
and error-prone.

As long as you realize this, though, you could possibly give it a shot
(here be dragons, you have been warned).

> unitReg=re.compile(r"\<unit\>(*)\</unit\>")

This is probably not what you actually did, because it fails with a
different error:

>>> a = re.compile(r"\<unit\>(*)\</unit\>")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/re.py",
line 188, in compile
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/re.py",
line 243, in _compile
sre_constants.error: nothing to repeat

I'll assume that said "(.*)". There's still a few problems: < and >
shouldn't be escaped, which is why you're not getting any matches.
Also you shouldn't use * because it is greedy, matching as much as
possible. So it would match everything in between the first <unit> and
the last </unit> tag in the file, including other <unit></unit> tags
that might show up. What you want is more like this:

unit_reg = re.compile(r"<unit>(.*?)</unit>")

Test it carefully, ditch elementtree, use as little regexes as
possible (string functions are your friends! startswith, split, strip,
et cetera) and you might end up with something that is only slightly
ugly and mostly works. That said, I'd still advise against it. turning
the files into valid XML and then using whatever XML parser you fancy
will probably be easier. Adding quotes and closing tags and removing
comments with regexes is still bad, but easier than parsing the whole
thing with regexes.

HTH,
Hugo

From lie.1296 at gmail.com  Sat Jan  7 21:25:57 2012
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sun, 08 Jan 2012 07:25:57 +1100
Subject: [Tutor] Subclassing Exceptions
In-Reply-To: <4F07D080.8080600@pearwood.info>
References: <201201062124.41384.cfuller084@thinkingplanet.net>
	<4F07D080.8080600@pearwood.info>
Message-ID: <jea9ol$1jm$1@dough.gmane.org>

On 01/07/2012 03:56 PM, Steven D'Aprano wrote:
> Chris Fuller wrote:
>
> You probably shouldn't inherit from SyntaxError, since it represents
> syntax errors in the Python code being interpreted or compiled. Any
> syntax error in your own data structures should be independent of
> SyntaxError.

I'd say a syntactical error in your own data structure is a kind of 
ValueError.


From lie.1296 at gmail.com  Sat Jan  7 22:51:58 2012
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sun, 08 Jan 2012 08:51:58 +1100
Subject: [Tutor] making a custom file parser?
In-Reply-To: <CAF=P20UoF7Fn5W+qnpO1rASQVJbYKDQ0sBC9-rpWm3Hvhit7Tg@mail.gmail.com>
References: <CAF=P20UoF7Fn5W+qnpO1rASQVJbYKDQ0sBC9-rpWm3Hvhit7Tg@mail.gmail.com>
Message-ID: <jeaepv$a0$1@dough.gmane.org>

On 01/08/2012 04:53 AM, Alex Hall wrote:
> Hello all,
> I have a file with xml-ish code in it, the definitions for units in a
> real-time strategy game. I say xml-ish because the tags are like xml,
> but no quotes are used and most tags do not have to end. Also,
> comments in this file are prefaced by an apostrophe, and there is no
> multi-line commenting syntax. For example:
>
> <unit>
> <number=1>
> <name=my unit>
> <canMove=True>
> <canCarry=unit2, unit3, unit4>
> 'this line is a comment
> </unit>
>

The format is closer to sgml than to xml, except for the tag being able 
to have values. I'd say you probably would have a better chance of 
transforming this into sgml than transforming it to xml.

Try this re:

s = re.sub('<([a-zA-Z]+)=([^>]+)>', r'<\1 __attribute__="\2">', s)

and use an SGML parser to parse the result. I find Fredrik Lundh's 
sgmlop to be easier to use for this one, just use easy_install or pip to 
install sgmlop.

import sgmlop

class Unit(object): pass

class handler:
     def __init__(self):
         self.units = {}
     def finish_starttag(self, tag, attrs):
         attrs = dict(attrs)
         if tag == 'unit':
             self.current = Unit()
         elif tag == 'number':
             self.current.number = int(attrs['__attribute__'])
         elif tag == 'canmove':
             self.current.canmove = attrs['__attribute__'] == 'True'
         elif tag in ('name', 'cancarry'):
             setattr(self.current, tag, attrs['__attribute__'])
         else:
             print 'unknown tag', tag, attrs
     def finish_endtag(self, tag):
         if tag == 'unit':
             self.units[self.current.name] = self.current
             del self.current
     def handle_data(self, data):
         if not data.isspace(): print data.strip()

s = '''
<unit>
<number=1>
<name=my unit>
<canMove=True>
<canCarry=your unit, her unit, his unit>
'this line is a comment
</unit>
<unit>
<number=2>
<name=your unit>
<canMove=False>
<canCarry=her unit, his unit>
'this line is a comment
</unit>
<unit>
<number=3>
<name=her unit>
<canMove=True>
<canCarry=her unit>
'this line is a comment
</unit>
<unit>
<number=4>
<name=his unit>
<canMove=True>
<canCarry=his unit, her unit>
'this line is a comment
</unit>
'''
s = re.sub('<([a-zA-Z]+)=([^>]+)>', r'<\1 __attribute__="\2">', s)
parser = sgmlop.SGMLParser()
h = handler()
parser.register(h)
parser.parse(s)
print h.units


From sierra_mtnview at sbcglobal.net  Sat Jan  7 23:13:34 2012
From: sierra_mtnview at sbcglobal.net (Wayne Watson)
Date: Sat, 07 Jan 2012 14:13:34 -0800
Subject: [Tutor] Return to my python26.dll & python.dll problems on
	bootup
In-Reply-To: <4F05EB22.5080808@pearwood.info>
References: <4F05E027.7010400@sbcglobal.net> <4F05EB22.5080808@pearwood.info>
Message-ID: <4F08C38E.2060803@sbcglobal.net>

You are right about posting here, but I was hoping someone might have 
related to the problem. I went to the WinAmp forum for help. But who 
would have guessed that WinAmp would have provided a program not ready 
for prime time, and nothing buy an advertisement to get you to buy the 
latest drivers for your PC.  Lesson learned.  Someone on their forum 
suggested hijackthis.log, which will fix a registry.  Five stars by 
CNET, but it may not be quite free.  Ah, I just got through to uniblue's 
tech support by mail.

As an aside, I've noticed that a lot of downloadable freebies have pages 
that are thick  with other $ products advertising. Once you get through 
several pages of them, you then find the download.

On 1/5/2012 10:25 AM, Steven D'Aprano wrote:
> Wayne Watson wrote:
>>   I have two problems upon bootup of my Win7 PC, 64-bit.
>
> Wayne, I sympathize with your problems, but they are Windows problems, 
> not Python problems, and have absolutely nothing to do with learning 
> to program Python. You are spamming this mailing list with off-topic 
> questions about fixing your Windows system. This list is about 
> learning Python programming, not "we'll fix any problem that has some 
> vague connection to Python, no matter how slight". Have you tried 
> asking for help on Windows-related forums or mailing lists?
>
> It has been many years since I've used Windows regularly, but I can 
> tell you this: you don't do yourself any favours by installing and 
> uninstalling programs under Windows. I know it is less than helpful, 
> but my advice is *never* install any program you aren't sure you will 
> want to keep, because uninstalling always leaves traces of crud 
> behind, eventually leading to exactly the sorts of problems you are 
> experiencing.
>
>
>

-- 
            Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

              (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
               Obz Site:  39? 15' 7" N, 121? 2' 32" W, 2700 feet

                      CE 1955 October 20 07:53:32.6 UT
                     -- "The Date" The mystery unfolds.

                     Web Page:<www.speckledwithstars.net/>



From rhettnaxel at gmail.com  Sun Jan  8 17:54:24 2012
From: rhettnaxel at gmail.com (Alexander Etter)
Date: Sun, 8 Jan 2012 11:54:24 -0500
Subject: [Tutor] Zip, tar, and file handling
In-Reply-To: <2012010711570599909815@126.com>
References: <2012010711570599909815@126.com>
Message-ID: <5BD51F94-4374-4566-BA80-440F1A9C610B@gmail.com>


On Jan 6, 2012, at 22:57, daedae11 <daedae11 at 126.com> wrote:

> I was asked to write a program to move files between ZIP(.zip) and TAR/GZIP(.tgz/.tar.gz) or TAR/BZIP2(.tbz/.tar.bz2) archive.
>  
> my code is:
>  
>  
> import zipfile;
> import tarfile;
> import os;
> from os import path ;
>  
> def showAllFiles(fileObj):
>     if fileObj.filename.endswith("zip"):
>         if isinstance(fileObj, zipfile.ZipFile):
>             print "j"*20;
>         for name in fileObj.namelist():
>             print name;
>     else:
>         for name in fileObj.getnames():
>             print name; 
>  
> def moveFile(srcObj, dstObj):
>     fileName = raw_input("input the name of the file to move: ");    
>     srcObj.extract(fileName);
>     if isinstance(dstObj, zipfile.ZipFile):
>         dstObj.write(fileName);
>     else:
>         dstObj.addfile(tarfile.TarInfo(fileName));
>     os.remove(fileName);    
>     
> def main():
>     intro = """
> enter a choice
> (M)ove file from source file to destinatiom file
> (S)how all the files in source file
> (Q)uit
> your choice is: """    
>     srcFile = raw_input("input the source file name: ");
>     dstFile = raw_input("input the destination file name: ");
>     while True:
>         with ( zipfile.ZipFile(srcFile, "r") if srcFile.endswith("zip") else tarfile.open(srcFile, "r"+":"+path.splitext(srcFile)[1][1:]) ) as srcObj, \
>         ( zipfile.ZipFile(dstFile, "r") if
>            dstFile.endswith("zip") else
>             tarfile.open(dstFile, "w"+":"+path.splitext(dstFile)[1][1:]) ) as dstObj:        
>                 choice = raw_input(intro)[0].lower();
>                 if choice == "s":
>                     showAllFiles(srcObj);
>                 elif choice == "m":
>                     moveFile(srcObj, dstObj);
>                 elif choice == "q":
>                     break;
>                 else:
>                     print "invalid command!"
>  
> if __name__ == '__main__':
>     main();
>  
> But there are some problems.
> 1. It could extract file successfully, but can't add files to .tar.gz file.
> 2. I think it's a little tedious, but I don't know how to improve it.
>  
> Please  give me some help , thank you!
>  
> daedae11
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Hi there. I would start by handling file extensions other than ZIP in your first two functions. Why not handle if the file is a tgz or tbz within the functions. Also I don't see the purpose of the first function, "showallfiles" it prints out twenty "j"s?
Looking forward to your response. 
Alexander
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120108/2eb44e6a/attachment.html>

From adamgold at hotmail.com  Mon Jan  9 00:34:15 2012
From: adamgold at hotmail.com (Adam Gold)
Date: Sun, 8 Jan 2012 23:34:15 +0000
Subject: [Tutor] different behaviour in Idle shell vs Mac terminal
Message-ID: <BAY154-W33B0B74ECB8CAC2C219E53C69B0@phx.gbl>


I have short piece of code I'm using to print a string to the terminal one letter at a time.? It works fine when I invoke the script from within Idle; each letter appears after the preceding one according to the designated time interval.? However if I run it in the Mac terminal ('python3 ./script.py'), there's a pause and then the whole string prints in one go.? Here's the relevant code:

import sys
import time

text = "this text is printing one letter at a time..."
for char in text:
??? sys.stdout.write(char)
??? time.sleep(0.03)

I'm thinking this may be a tty issue (is stdout going to the right terminal?) but I'm still finding my way and would therefore appreciate any guidance.? Of course if there's a better way of printing out one letter at a time, I'm also interested to know that.? Thanks.

P.S. if it's relevant, this is part of a simple financial maths program and it's used to display the results after certain inputs have been gathered.
 		 	   		  

From steve at pearwood.info  Mon Jan  9 00:56:29 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 09 Jan 2012 10:56:29 +1100
Subject: [Tutor] different behaviour in Idle shell vs Mac terminal
In-Reply-To: <BAY154-W33B0B74ECB8CAC2C219E53C69B0@phx.gbl>
References: <BAY154-W33B0B74ECB8CAC2C219E53C69B0@phx.gbl>
Message-ID: <4F0A2D2D.9000809@pearwood.info>

Adam Gold wrote:
> I have short piece of code I'm using to print a string to the terminal one letter at a time.  It works fine when I invoke the script from within Idle; each letter appears after the preceding one according to the designated time interval.  However if I run it in the Mac terminal ('python3 ./script.py'), there's a pause and then the whole string prints in one go.  Here's the relevant code:
> 
> import sys
> import time
> 
> text = "this text is printing one letter at a time..."
> for char in text:
>     sys.stdout.write(char)
>     time.sleep(0.03)
> 
> I'm thinking this may be a tty issue (is stdout going to the right terminal?)

It's a buffering issue.

[...]
> P.S. if it's relevant, this is part of a simple financial maths program and it's used to display the results after certain inputs have been gathered.

To annoy your users? I'm not sure why you think it's a good idea to pretend 
that the computer has to type the letters one at a time. This isn't some 
stupid imaginary program in a Hollywood movie, I assume it is meant to 
actually be useful and usable, and trust me on this, waiting while the program 
pretends to type gets old *really* fast.

(What are you trying to emulate? A stock ticker or something? Do those things 
still even exist? I haven't seen one since the last time I watched the Addams 
Family TV series. The old one, in black & white.)

But if you must, after writing each character, call sys.stdout.flush() to 
flush the buffer.



-- 
Steven


From alan.gauld at btinternet.com  Mon Jan  9 01:03:10 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 09 Jan 2012 00:03:10 +0000
Subject: [Tutor] different behaviour in Idle shell vs Mac terminal
In-Reply-To: <BAY154-W33B0B74ECB8CAC2C219E53C69B0@phx.gbl>
References: <BAY154-W33B0B74ECB8CAC2C219E53C69B0@phx.gbl>
Message-ID: <jedaru$4ug$1@dough.gmane.org>

On 08/01/12 23:34, Adam Gold wrote:
>
> I have short piece of code I'm using to print a string to
 > the terminal one letter at a time.  It works fine when
> I invoke the script from within Idle; each letter appears
> afterthe preceding one according to the designated time
 > interval.
 > However if I run it in the Mac terminal
 > ('python3 ./script.py'),
 > there's a pause and then the whole string prints in one go.

Thats because you are writing to stdout rather than using print
The output is buffered and the terminal prints the output after the 
bufrfer is flushed, which happens at the end of the program
(probably when the file object is auto closed). if you use print
that shouldn't happen.

The alternative is to explicitly flush() the file after each write.

> import sys
> import time
>
> text = "this text is printing one letter at a time..."
> for char in text:
>      sys.stdout.write(char)

either use
        print char,    # comma suppresses \n

or

       sys.stdout.write(char)
       sys.stdout.flush()

HTH

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


From jeanpierreda at gmail.com  Mon Jan  9 02:19:46 2012
From: jeanpierreda at gmail.com (Devin Jeanpierre)
Date: Sun, 8 Jan 2012 20:19:46 -0500
Subject: [Tutor] making a custom file parser?
In-Reply-To: <CAJmBOf=9dcrR=iw3-04vUtH0ND4Smf2H92vpTvks8mvPkDQxkw@mail.gmail.com>
References: <CAF=P20UoF7Fn5W+qnpO1rASQVJbYKDQ0sBC9-rpWm3Hvhit7Tg@mail.gmail.com>
	<201201071301.21959.cfuller084@thinkingplanet.net>
	<CAF=P20XjYM1C0XycnWKFHwg8SRgPNJ8k8Eduk=SAj9NCazYbVA@mail.gmail.com>
	<CAJmBOf=9dcrR=iw3-04vUtH0ND4Smf2H92vpTvks8mvPkDQxkw@mail.gmail.com>
Message-ID: <CABicbJKVWR7bo9fQ3W91VMZ4sXtB62kp6WTQ2PV-fO7nwMjCow@mail.gmail.com>

> Parsing XML with regular expressions is generally very bad idea. In
> the general case, it's actually impossible. XML is not what is called
> a regular language, and therefore cannot be parsed with regular
> expressions. You can use regular expressions to grab a limited amount
> of data from a limited set of XML files, but this is dangerous, hard,
> and error-prone.

Python regexes aren't regular, and this isn't XML.

A working XML parser has been written using .NET regexes (sorry, no
citation -- can't find it), and they only have one extra feature
(recursion, of course). And it was dreadfully ugly and nasty and
probably terrible to maintain -- that's the real cost of regexes.

In particular, his data actually does look regular.

> I'll assume that said "(.*)". There's still a few problems: < and >
> shouldn't be escaped, which is why you're not getting any matches.
> Also you shouldn't use * because it is greedy, matching as much as
> possible. So it would match everything in between the first <unit> and
> the last </unit> tag in the file, including other <unit></unit> tags
> that might show up.

On the "can you do work with this with regexes" angle: if units can be
nested, then neither greedy nor non-greedy matching will work. That's
a particular case where regular expressions can't work for your data.

> Test it carefully, ditch elementtree, use as little regexes as
> possible (string functions are your friends! startswith, split, strip,
> et cetera) and you might end up with something that is only slightly
> ugly and mostly works. That said, I'd still advise against it. turning
> the files into valid XML and then using whatever XML parser you fancy
> will probably be easier.

He'd probably do that using regexes.

Easiest way is probably to write a real parser using some PEG or CFG
thingy. Less error-prone.

Overall agree with advice, though. Just being picky. Sorry.

-- Devin


On Sat, Jan 7, 2012 at 3:15 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote:
> On Sat, Jan 7, 2012 at 8:22 PM, Alex Hall <mehgcap at gmail.com> wrote:
>> I had planned to parse myself, but am not sure how to go about it. I
>> assume regular expressions, but I couldn't even find the amount of
>> units in the file by using:
>> unitReg=re.compile(r"\<unit\>(*)\</unit\>")
>> unitCount=unitReg.search(fileContents)
>> print "number of units: "+unitCount.len(groups())
>>
>> I just get an exception that "None type object has no attribute
>> groups", meaning that the search was unsuccessful. What I was hoping
>> to do was to grab everything between the opening and closing unit
>> tags, then read it one at a time and parse further. There is a tag
>> inside a unit tag called AttackTable which also terminates, so I would
>> need to pull that out and work with it separately. I probably just
>> have misunderstood how regular expressions and groups work...
>>
>
> Parsing XML with regular expressions is generally very bad idea. In
> the general case, it's actually impossible. XML is not what is called
> a regular language, and therefore cannot be parsed with regular
> expressions. You can use regular expressions to grab a limited amount
> of data from a limited set of XML files, but this is dangerous, hard,
> and error-prone.
>
> As long as you realize this, though, you could possibly give it a shot
> (here be dragons, you have been warned).
>
>> unitReg=re.compile(r"\<unit\>(*)\</unit\>")
>
> This is probably not what you actually did, because it fails with a
> different error:
>
>>>> a = re.compile(r"\<unit\>(*)\</unit\>")
> Traceback (most recent call last):
> ?File "<stdin>", line 1, in <module>
> ?File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/re.py",
> line 188, in compile
> ?File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/re.py",
> line 243, in _compile
> sre_constants.error: nothing to repeat
>
> I'll assume that said "(.*)". There's still a few problems: < and >
> shouldn't be escaped, which is why you're not getting any matches.
> Also you shouldn't use * because it is greedy, matching as much as
> possible. So it would match everything in between the first <unit> and
> the last </unit> tag in the file, including other <unit></unit> tags
> that might show up. What you want is more like this:
>
> unit_reg = re.compile(r"<unit>(.*?)</unit>")
>
> Test it carefully, ditch elementtree, use as little regexes as
> possible (string functions are your friends! startswith, split, strip,
> et cetera) and you might end up with something that is only slightly
> ugly and mostly works. That said, I'd still advise against it. turning
> the files into valid XML and then using whatever XML parser you fancy
> will probably be easier. Adding quotes and closing tags and removing
> comments with regexes is still bad, but easier than parsing the whole
> thing with regexes.
>
> HTH,
> Hugo
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From hugo.yoshi at gmail.com  Mon Jan  9 03:06:12 2012
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Mon, 9 Jan 2012 03:06:12 +0100
Subject: [Tutor] making a custom file parser?
In-Reply-To: <CABicbJKVWR7bo9fQ3W91VMZ4sXtB62kp6WTQ2PV-fO7nwMjCow@mail.gmail.com>
References: <CAF=P20UoF7Fn5W+qnpO1rASQVJbYKDQ0sBC9-rpWm3Hvhit7Tg@mail.gmail.com>
	<201201071301.21959.cfuller084@thinkingplanet.net>
	<CAF=P20XjYM1C0XycnWKFHwg8SRgPNJ8k8Eduk=SAj9NCazYbVA@mail.gmail.com>
	<CAJmBOf=9dcrR=iw3-04vUtH0ND4Smf2H92vpTvks8mvPkDQxkw@mail.gmail.com>
	<CABicbJKVWR7bo9fQ3W91VMZ4sXtB62kp6WTQ2PV-fO7nwMjCow@mail.gmail.com>
Message-ID: <CAJmBOfn-DBXdYsSC1=h3snbK1mL8XCFzeARvOzOnMMJzXhSnUQ@mail.gmail.com>

On Mon, Jan 9, 2012 at 2:19 AM, Devin Jeanpierre <jeanpierreda at gmail.com> wrote:
>> Parsing XML with regular expressions is generally very bad idea. In
>> the general case, it's actually impossible. XML is not what is called
>> a regular language, and therefore cannot be parsed with regular
>> expressions. You can use regular expressions to grab a limited amount
>> of data from a limited set of XML files, but this is dangerous, hard,
>> and error-prone.
>
> Python regexes aren't regular, and this isn't XML.
>
> A working XML parser has been written using .NET regexes (sorry, no
> citation -- can't find it), and they only have one extra feature
> (recursion, of course). And it was dreadfully ugly and nasty and
> probably terrible to maintain -- that's the real cost of regexes.
>

IIRC, Python's only non-regular feature is backreferences though; I'm
pretty sure that isn't enough to parse XML. It does not make it
powerful enough to parse context-free languages. I really would like
that citation though, tried googling for it but not much turned up.
I'm not calling bs or anything, I don't know anything about .net
regexes and I'll readily believe it can be done (I just want to see
the code for myself). But really I still wouldn't dare try without a
feature set like perl 6's regexes. And even then..

You're technically correct (it's the best kind), but I feel like it
doesn't really take away the general correctness of my advice ;)

> In particular, his data actually does look regular.
>

Quite right. We haven't seen enough of it to be sure, but that little
bite seems parseable enough with some basic string methods and one or
two regexes. That's really all you need, and trying to do the whole
thing with pure regex is just needlessly overcomplicating things (I'm
pretty sure we all actually agree on that).

>> I'll assume that said "(.*)". There's still a few problems: < and >
>> shouldn't be escaped, which is why you're not getting any matches.
>> Also you shouldn't use * because it is greedy, matching as much as
>> possible. So it would match everything in between the first <unit> and
>> the last </unit> tag in the file, including other <unit></unit> tags
>> that might show up.
>
> On the "can you do work with this with regexes" angle: if units can be
> nested, then neither greedy nor non-greedy matching will work. That's
> a particular case where regular expressions can't work for your data.
>
>> Test it carefully, ditch elementtree, use as little regexes as
>> possible (string functions are your friends! startswith, split, strip,
>> et cetera) and you might end up with something that is only slightly
>> ugly and mostly works. That said, I'd still advise against it. turning
>> the files into valid XML and then using whatever XML parser you fancy
>> will probably be easier.
>
> He'd probably do that using regexes.
>

Yeah, that's what I was thinking when I said it too. Something like,
one regex to quote attributes, and one that adds close tags at the
earliest opportunity. Like right before a newline? It looks okay based
on just that sample, but it's really hard to say. The viability of
regexes depends so much on the dataset you have. If you can make the
dataset valid XML with just three regexes (quotes, end tags, comments)
then just parse it that way, that sounds like the simplest possible
option.

> Easiest way is probably to write a real parser using some PEG or CFG
> thingy. Less error-prone.
>

You mean like flex/bison? May be overkill, but then again, maybe not.
So much depends on the data.

> Overall agree with advice, though. Just being picky. Sorry.
>
> -- Devin
>
>

I love being picky myself, so I don't mind, as long as there is a
disclaimer somewhere ;) Cheers,
Hugo

From leamhall at gmail.com  Mon Jan  9 03:09:28 2012
From: leamhall at gmail.com (Leam Hall)
Date: Sun, 08 Jan 2012 21:09:28 -0500
Subject: [Tutor] Moving from snippits to large projects?
Message-ID: <4F0A4C58.9070405@gmail.com>

I'm taking the O'Reilly Python 2 course on-line, and enjoying it. Well, 
when Eclipse works, anyway. I'm still getting the hang of that.

While my coding over the years has been small snippits in shell, PHP, 
and a little C, python, and perl, I've never made the transition from 
dozens of lines to hundreds or thousands. I'd like to start working on 
that transition but the projects I know about are much larger than my 
brain can handle and there are a lot of other corollary tools and 
practices to learn.

How does one go from small to medium, to large, as a coder? Large 
projects, that is. I've gotten the "large as in too much pizza" thing 
down.  ;)

Leam

From hugo.yoshi at gmail.com  Mon Jan  9 05:45:35 2012
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Mon, 9 Jan 2012 05:45:35 +0100
Subject: [Tutor] Moving from snippits to large projects?
In-Reply-To: <4F0A4C58.9070405@gmail.com>
References: <4F0A4C58.9070405@gmail.com>
Message-ID: <CAJmBOfkD5kRosq=sJXiu4VGipBkN+TkRCO7nmURnDY9Gi+OLwA@mail.gmail.com>

On Mon, Jan 9, 2012 at 3:09 AM, Leam Hall <leamhall at gmail.com> wrote:
> I'm taking the O'Reilly Python 2 course on-line, and enjoying it. Well, when
> Eclipse works, anyway. I'm still getting the hang of that.
>
> While my coding over the years has been small snippits in shell, PHP, and a
> little C, python, and perl, I've never made the transition from dozens of
> lines to hundreds or thousands. I'd like to start working on that transition
> but the projects I know about are much larger than my brain can handle and
> there are a lot of other corollary tools and practices to learn.
>
> How does one go from small to medium, to large, as a coder? Large projects,
> that is. I've gotten the "large as in too much pizza" thing down. ?;)
>

Well, the best advice I could offer is to get in over your head. Pick
a large project, think a bit about how you'd structure it, then jump
right in! This is what I did, and the result was that I learned so
much that I abandoned it about halfway through and started over,
saying "I went about this totally wrong, let's get it right this
time!"

That process repeated itself a lot of times, and each time I came out
with new lessons learned about how to structure large projects.
Honestly, learning by doing is the best. You'll be unhappy about a ton
of your projects, abandon some, finish others (honestly, just
finishing something should be enough to be proud of by my standards).
The important thing is to just code and realize it's ok to not know
what you're doing most of the time (well, as long as you're not
getting paid for it anyway).

A few things are invaluable when working with larger projects:

- the python debugger, pdb. Debugging with print statements is fine
for smaller stuff, but for complicated software, a debugger is a nice
tool to have
- version control. Crucial for working in a team, but even coding solo
working on something big it's nice to have branches and rollbacks.
You'd be best off just getting used to this and using it for all
projects. I work with git, but anything is better than nothing. pick
up a popular one and go with it.
- unit testing. Some people consider this optional (I never actually
got into it myself), but it's worth taking a look at.

I won't go into detail concerning any of these. None of them are
python specific anyway. I suggest you google them yourself and learn
gradually, by doing. It's the best way.

HTH,
Hugo

From __peter__ at web.de  Mon Jan  9 10:05:47 2012
From: __peter__ at web.de (Peter Otten)
Date: Mon, 09 Jan 2012 10:05:47 +0100
Subject: [Tutor] different behaviour in Idle shell vs Mac terminal
References: <BAY154-W33B0B74ECB8CAC2C219E53C69B0@phx.gbl>
	<jedaru$4ug$1@dough.gmane.org>
Message-ID: <jeeal7$cp8$1@dough.gmane.org>

Alan Gauld wrote:

> On 08/01/12 23:34, Adam Gold wrote:
>>
>> I have short piece of code I'm using to print a string to
>  > the terminal one letter at a time.  It works fine when
>> I invoke the script from within Idle; each letter appears
>> afterthe preceding one according to the designated time
>  > interval.
>  > However if I run it in the Mac terminal
>  > ('python3 ./script.py'),
>  > there's a pause and then the whole string prints in one go.
> 
> Thats because you are writing to stdout rather than using print
> The output is buffered and the terminal prints the output after the
> bufrfer is flushed, which happens at the end of the program
> (probably when the file object is auto closed). if you use print
> that shouldn't happen.
> 
> The alternative is to explicitly flush() the file after each write.
> 
>> import sys
>> import time
>>
>> text = "this text is printing one letter at a time..."
>> for char in text:
>>      sys.stdout.write(char)
> 
> either use
>         print char,    # comma suppresses \n

The newline will be suppressed, but the next print statement will inject a 
space before dumping its arguments. Also, you still need to flush(). That 
makes a working print-based solution a bit esoteric:

for c in text:
    print c,
    sys.stdout.softspace = False
    sys.stdout.flush()
    time.sleep(.3)



From bugcy013 at gmail.com  Mon Jan  9 10:17:46 2012
From: bugcy013 at gmail.com (Ganesh Kumar)
Date: Mon, 9 Jan 2012 14:47:46 +0530
Subject: [Tutor] re module help
Message-ID: <CAJzooYe5Tu20aF6gpM+JTfNkQgeskWwJha-T=OHFi7HLMZ9jOQ@mail.gmail.com>

Hi Gurus,

I have created regular expression with os modules, I have created file
sdptool to match the regular expression pattern, will print the result.
I want without creating file how to get required output, I tried but i
didn't get output correctly, over stream.

#! /usr/bin/python
import os,re

def scan():

    cmd = "sdptool -i hci0 search OPUSH > sdptool"
    fp = os.popen(cmd)

    results = []
    l = open("sdptool").read()


    pattern = r"^Searching for OPUSH on (\w\w(:\w\w)+).*?Channel: (\d+)"
    r = re.compile(pattern, flags=re.MULTILINE|re.DOTALL)
    while True:
        for match in r.finditer(l):
            g  = match.groups()

            results.append((g[0],'phone',g[2]))
            return results

## output [('00:15:83:3D:0A:57', 'phone', '1')]


http://dpaste.com/684335/
please guide me. with out file creating, to archive required output.


Did I learn something today? If not, I wasted it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120109/e92b3898/attachment.html>

From steve at pearwood.info  Mon Jan  9 11:31:34 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 09 Jan 2012 21:31:34 +1100
Subject: [Tutor] Moving from snippits to large projects?
In-Reply-To: <4F0A4C58.9070405@gmail.com>
References: <4F0A4C58.9070405@gmail.com>
Message-ID: <4F0AC206.6010903@pearwood.info>

Leam Hall wrote:
> I'm taking the O'Reilly Python 2 course on-line, and enjoying it. Well, 
> when Eclipse works, anyway. I'm still getting the hang of that.
> 
> While my coding over the years has been small snippits in shell, PHP, 
> and a little C, python, and perl, I've never made the transition from 
> dozens of lines to hundreds or thousands. I'd like to start working on 
> that transition but the projects I know about are much larger than my 
> brain can handle and there are a lot of other corollary tools and 
> practices to learn.
> 
> How does one go from small to medium, to large, as a coder? Large 
> projects, that is.


Pick something useful which you would like. Write the program. That might be a 
few dozen lines.

Stage 2: pretend that other people will use it, people who don't know how it 
is supposed to work, so put in plenty of error checking. Before you know it, 
you've got 100-200 lines of code.

Then add documentation. There's another 200-400 lines. (Except for the most 
trivial programs, in my experience documentation will be about double the size 
of the code you are documenting, at least the way I write it, with plenty of 
detail and examples.)

Now write extensive tests for it. Ideally, you should test every function and 
class in the program. You should test that it works as expected with good 
input, and fails as expected with bad input. That's another 400-800 lines. (In 
my experience, proper testing will be at least four times as big as the code 
you are testing.)

And lo and behold, you now have a medium-sized project. A *large* project will 
be tens of thousands of lines, not hundreds. A *major* project will be 
millions of lines.

Here's an example: I wrote a script to download images from the Quickmeme 
website. http://www.quickmeme.com/Web-Developer-Walrus/

Even without moving onto stage 2, I have 120 lines of code and documentation.

If I were to continue to work on it, I'd start adapting the script to be more 
generic. Turn it a general purpose "download anything from anywhere" library 
(a bit like wget or curl, for those who know those tools). Off the top of my 
head, I expect that would require 500-1000 lines of Python code and 
documentation. Plus tests.



-- 
Steven


From leamhall at gmail.com  Mon Jan  9 12:00:51 2012
From: leamhall at gmail.com (Leam Hall)
Date: Mon, 09 Jan 2012 06:00:51 -0500
Subject: [Tutor] Moving from snippits to large projects?
In-Reply-To: <4F0AC206.6010903@pearwood.info>
References: <4F0A4C58.9070405@gmail.com> <4F0AC206.6010903@pearwood.info>
Message-ID: <4F0AC8E3.8000601@gmail.com>

> Leam Hall wrote:
 >> Steve and Hugo Responded

 > To which Leam Replies:

Thanks! The O'Reilly class has twelve lessons, the first two are on unit 
testing. The rest of them will enforce tests be written for their 
projects.  :)

I'll look at Git and Sourceforge in the next couple days. In theory I'd 
like to get to kernel programming so Git would be useful. However, it 
doesn't have the Software Lifecycle tools Sourceforge has.

One of the problems with Python is that the neat things I'd like to 
write and use are already written! Well, there are things I need to 
learn, like Sphinx, Twisted, and maybe CherryPy. As well as PDB and 
better unittests.

So much to learn! I'm happy...

Leam

From adamgold at hotmail.com  Mon Jan  9 12:40:38 2012
From: adamgold at hotmail.com (Adam Gold)
Date: Mon, 9 Jan 2012 11:40:38 +0000
Subject: [Tutor] different behaviour in Idle shell vs Mac terminal
In-Reply-To: <mailman.24548.1326072030.27777.tutor@python.org>
References: <mailman.24548.1326072030.27777.tutor@python.org>
Message-ID: <BAY154-W6583851AECCCCF204F556FC6980@phx.gbl>


> Date: Sun, 8 Jan 2012 23:34:15 +0000
> From: Adam Gold 
> To: 
> Subject: [Tutor] different behaviour in Idle shell vs Mac terminal
> Message-ID: 
> Content-Type: text/plain; charset="iso-8859-1"
>
>
> I have short piece of code I'm using to print a string to the terminal one letter at a time.? It works fine when I invoke the script from within Idle; each letter appears after the preceding one according to the designated time interval.? However if I run it in the Mac terminal ('python3 ./script.py'), there's a pause and then the whole string prints in one go.? Here's the relevant code:
>
> import sys
> import time
>
> text = "this text is printing one letter at a time..."
> for char in text:
> ??? sys.stdout.write(char)
> ??? time.sleep(0.03)
>
> I'm thinking this may be a tty issue (is stdout going to the right terminal?) but I'm still finding my way and would therefore appreciate any guidance.? Of course if there's a better way of printing out one letter at a time, I'm also interested to know that.? Thanks.
>
> P.S. if it's relevant, this is part of a simple financial maths program and it's used to display the results after certain inputs have been gathered.
>
>
> ------------------------------
>
> Message: 3
> Date: Mon, 09 Jan 2012 10:56:29 +1100
> From: Steven D'Aprano 
> To: tutor at python.org
> Subject: Re: [Tutor] different behaviour in Idle shell vs Mac terminal
> Message-ID: <4F0A2D2D.9000809 at pearwood.info>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Adam Gold wrote:
> > I have short piece of code I'm using to print a string to the terminal one letter at a time. It works fine when I invoke the script from within Idle; each letter appears after the preceding one according to the designated time interval. However if I run it in the Mac terminal ('python3 ./script.py'), there's a pause and then the whole string prints in one go. Here's the relevant code:
> >
> > import sys
> > import time
> >
> > text = "this text is printing one letter at a time..."
> > for char in text:
> > sys.stdout.write(char)
> > time.sleep(0.03)
> >
> > I'm thinking this may be a tty issue (is stdout going to the right terminal?)
>
> It's a buffering issue.
>
> [...]
> > P.S. if it's relevant, this is part of a simple financial maths program and it's used to display the results after certain inputs have been gathered.
>
> To annoy your users? I'm not sure why you think it's a good idea to pretend
> that the computer has to type the letters one at a time. This isn't some
> stupid imaginary program in a Hollywood movie, I assume it is meant to
> actually be useful and usable, and trust me on this, waiting while the program
> pretends to type gets old *really* fast.
>
> (What are you trying to emulate? A stock ticker or something? Do those things
> still even exist? I haven't seen one since the last time I watched the Addams
> Family TV series. The old one, in black & white.)
>
> But if you must, after writing each character, call sys.stdout.flush() to
> flush the buffer.
>
>
>
> --
> Steven
>
Thanks Steven that worked.? In terms of why I'm using this: I shouldn't overstate what I'm doing when I say financial maths.? One of the elements is a mortgage calculator for my mother who's, shall we say, not a "power user".? After taking the basic inputs, it prints out a few stats (monthly payment etc.).? Without some literal "brake" in how the info gets written on the screen, it all appears in one go and having tested it on said power user, it was too much at once.? Hence I want to slow things down.? I appreciate, I'm not pushing the boundaries here but one step at a time ('excuse the pun!).? Anyway, again, thanks for your help.
 		 	   		  

From daedae11 at 126.com  Mon Jan  9 13:24:06 2012
From: daedae11 at 126.com (daedae11)
Date: Mon, 9 Jan 2012 20:24:06 +0800
Subject: [Tutor] exception about "ctrl+c"
Message-ID: <201201092024059766976@126.com>

I want to catch the "ctrl+c" exception. My program is as following. But when I run my script and press "ctrl"+"c", the  program output nothing. I don't know where did I go wrong. Please help me. Thank you!

def safe_input(prompting):
    try:
        return raw_input(prompting);
    except KeyboardInterrupt, error:
        print error;
        return None;

def main():
    a = safe_input("input any thing!\n");
    print a;
    

if __name__ == '__main__':
    main();




daedae11
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120109/42ab6c1a/attachment.html>

From tvssarma.omega9 at gmail.com  Mon Jan  9 13:31:37 2012
From: tvssarma.omega9 at gmail.com (Sarma Tangirala)
Date: Mon, 9 Jan 2012 18:01:37 +0530
Subject: [Tutor] Sorting Nested Lists
Message-ID: <CABFCkKSci2f_rKztdhqtQecsqc1D3N-katx2Ns9WLF3D5hwVkA@mail.gmail.com>

Hi list,

I was banging my head about a pythonic way of doing the following,

Given a nested list, how do I sort the uppermost list based on one key and
when a special condition occurs a sort on another key should be performed?

For example, [[1,2], [2, 2], [3, 2], [4, 0]] would be sorted, in my example
as, [[4, 0], [3, 2], [2, 2], [1, 2]]. That is, sort on the second value and
in case they are equal, reverse sort on the first value.

I tried doing this using sorted and using a custom cmp function but not
sure about how to define the cmp function.

-- 
Sarma Tangirala,
Class of 2012,
Department of Information Science and Technology,
College of Engineering Guindy - Anna University
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120109/487d9353/attachment.html>

From bodsda at googlemail.com  Mon Jan  9 13:33:53 2012
From: bodsda at googlemail.com (bodsda at googlemail.com)
Date: Mon, 9 Jan 2012 12:33:53 +0000
Subject: [Tutor] re module help
In-Reply-To: <CAJzooYe5Tu20aF6gpM+JTfNkQgeskWwJha-T=OHFi7HLMZ9jOQ@mail.gmail.com>
References: <CAJzooYe5Tu20aF6gpM+JTfNkQgeskWwJha-T=OHFi7HLMZ9jOQ@mail.gmail.com>
Message-ID: <244517085-1326112436-cardhu_decombobulator_blackberry.rim.net-824373923-@b14.c12.bise7.blackberry>

You could use read directly on the popen call to negate having to write to a file

output = os.popen(?sdptool -i hci0 search OPUSH?).read()

Bodsda
Sent from my BlackBerry? wireless device

-----Original Message-----
From: Ganesh Kumar <bugcy013 at gmail.com>
Sender: tutor-bounces+bodsda=googlemail.com at python.org
Date: Mon, 9 Jan 2012 14:47:46 
To: <tutor at python.org>
Subject: [Tutor] re module help

_______________________________________________
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 Jan  9 13:41:24 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 9 Jan 2012 07:41:24 -0500
Subject: [Tutor] exception about "ctrl+c"
In-Reply-To: <201201092024059766976@126.com>
References: <201201092024059766976@126.com>
Message-ID: <CAPM-O+zCQE3G4hqsaAyBSNdcFT3SU=Oiw0BDn1JmBOtswzdG-w@mail.gmail.com>

On Mon, Jan 9, 2012 at 7:24 AM, daedae11 <daedae11 at 126.com> wrote:
> I want to catch the "ctrl+c" exception. My program is as following. But when
> I run my script and press "ctrl"+"c", the? program output nothing. I don't
> know where did I go wrong. Please help me. Thank you!
>
> def?safe_input(prompting):
> ????try:
> ????????return?raw_input(prompting);
> ????except?KeyboardInterrupt,?error:
> ????????print?error;
> ????????return?None;
>
> def?main():
> ????a?=?safe_input("input?any?thing!\n");
> ????print?a;
>
>
> if?__name__?==?'__main__':
> ????main();
>
> ________________________________
> daedae11
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
  python ctl-c.py
  input any thing!
  fdsaj
  fdsaj
  python ctl-c.py
  input any thing!
  ^C
  None

I just got this from your code.  Seems to work on python 2.65, linux

Are you running it from a command line like:  python ctl-c.py
or are you running in a python shell?  If you are in a shell it might
be consuming the ctl-c before your program can


-- 
Joel Goldstick

From cwitts at compuscan.co.za  Mon Jan  9 13:30:19 2012
From: cwitts at compuscan.co.za (Christian Witts)
Date: Mon, 09 Jan 2012 14:30:19 +0200
Subject: [Tutor] exception about "ctrl+c"
In-Reply-To: <201201092024059766976@126.com>
References: <201201092024059766976@126.com>
Message-ID: <4F0ADDDB.8030503@compuscan.co.za>

On 2012/01/09 02:24 PM, daedae11 wrote:
> I want to catch the "ctrl+c" exception. My program is as following. 
> But when I run my script and press "ctrl"+"c", the  program output 
> nothing. I don't know where did I go wrong. Please help me. Thank you!
> def safe_input(prompting):
>     try:
>         return raw_input(prompting);
>     except KeyboardInterrupt, error:
>         print error;
>         return None;
> def main():
>     a = safe_input("input any thing!\n");
>     print a;
> if __name__ == '__main__':
>     main();
> ------------------------------------------------------------------------
> daedae11
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
def safe_input(prompting):
     try:
         return raw_input(prompting)
     except KeyboardInterrupt:
         print 'KeyboardInterrupt Issued'
         return None

That will work as intended, if you had your original `except 
KeyboardInterrupt, error:` and did a `print repr(error)` afterwards you 
will see it does not contain an error message as you perhaps wanted.

Also, Python does not require semi-colons to denote the end-of-line. It 
can be used if you want to have multiple statements on a single line though.

-- 

Christian Witts
Python Developer
//
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120109/8ad9de62/attachment.html>

From steve at pearwood.info  Mon Jan  9 13:56:22 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 09 Jan 2012 23:56:22 +1100
Subject: [Tutor] Sorting Nested Lists
In-Reply-To: <CABFCkKSci2f_rKztdhqtQecsqc1D3N-katx2Ns9WLF3D5hwVkA@mail.gmail.com>
References: <CABFCkKSci2f_rKztdhqtQecsqc1D3N-katx2Ns9WLF3D5hwVkA@mail.gmail.com>
Message-ID: <4F0AE3F6.7020508@pearwood.info>

Sarma Tangirala wrote:
> Hi list,
> 
> I was banging my head about a pythonic way of doing the following,
> 
> Given a nested list, how do I sort the uppermost list based on one key and
> when a special condition occurs a sort on another key should be performed?
> For example, [[1,2], [2, 2], [3, 2], [4, 0]] would be sorted, in my example
> as, [[4, 0], [3, 2], [2, 2], [1, 2]]. That is, sort on the second value and
> in case they are equal, reverse sort on the first value.

That is not exactly a good example. There are at least two other ways to get 
the result you show, both much more obvious:

py> L = [[1,2], [2, 2], [3, 2], [4, 0]]
py> list(reversed(L))
[[4, 0], [3, 2], [2, 2], [1, 2]]
py> sorted(L, reverse=True)
[[4, 0], [3, 2], [2, 2], [1, 2]]


If I ignore your example, and just use the description:

"sort on the second value, and in case they are equal, reverse sort on the 
first value"

the way to do this is with a double sort. Note that this works because 
Python's sort is stable: in the event of ties, the first item remains first. 
In earlier versions of Python, this was not always the case.

So, given this list:

L = [[1,2], [4,0], [3,2], [2,2], [5,1], [1,1]]

first sort in reverse by the first item, then by the second:


py> L.sort(key=lambda sublist: sublist[0], reverse=True)
py> L.sort(key=lambda sublist: sublist[1])
py> print L
[[4, 0], [5, 1], [1, 1], [3, 2], [2, 2], [1, 2]]



Note that using a key function is MUCH more efficient than a cmp function. 
Comparison functions end up doing much more work, and hence are very much 
slower, than a key function.

Also note that in recent versions of Python, you can do without the lambda 
function and use the special "itemgetter" function:


py> from operator import itemgetter
py> L = [[1,2], [4,0], [3,2], [2,2], [5,1], [1,1]]
py> L.sort(key=itemgetter(0), reverse=True)
py> L.sort(key=itemgetter(1))
py> print L
[[4, 0], [5, 1], [1, 1], [3, 2], [2, 2], [1, 2]]


Last but not least, I will show how to do it using a custom cmp function. But 
I recommend that you don't use this!

def my_cmp(list1, list2):
     x = cmp(list1[1], list2[1])
     if x == 0:  # a tie
         x = cmp(list2[0], list1[0])  # swap the order for reverse sort
         # or if you prefer, x = -cmp(list1[0], list2[0])
     return x

sorted(L, my_cmp)




-- 
Steven

From steve at pearwood.info  Mon Jan  9 13:58:36 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 09 Jan 2012 23:58:36 +1100
Subject: [Tutor] different behaviour in Idle shell vs Mac terminal
In-Reply-To: <BAY154-W6583851AECCCCF204F556FC6980@phx.gbl>
References: <mailman.24548.1326072030.27777.tutor@python.org>
	<BAY154-W6583851AECCCCF204F556FC6980@phx.gbl>
Message-ID: <4F0AE47C.40804@pearwood.info>

Adam Gold wrote:

> Thanks Steven that worked.  In terms of why I'm using this: I shouldn't
> overstate what I'm doing when I say financial maths.  One of the elements
> is a mortgage calculator for my mother who's, shall we say, not a "power
> user".  After taking the basic inputs, it prints out a few stats (monthly
> payment etc.).  Without some literal "brake" in how the info gets written
> on the screen, it all appears in one go and having tested it on said power
> user, it was too much at once.  Hence I want to slow things down.

My recommendation is to display a full line of text, then pause before the 
next line of text. Not one character at a time.


Regards,


-- 
Steven


From __peter__ at web.de  Mon Jan  9 14:05:23 2012
From: __peter__ at web.de (Peter Otten)
Date: Mon, 09 Jan 2012 14:05:23 +0100
Subject: [Tutor] Sorting Nested Lists
References: <CABFCkKSci2f_rKztdhqtQecsqc1D3N-katx2Ns9WLF3D5hwVkA@mail.gmail.com>
Message-ID: <jeeomg$r51$1@dough.gmane.org>

Sarma Tangirala wrote:

> I was banging my head about a pythonic way of doing the following,
> 
> Given a nested list, how do I sort the uppermost list based on one key and
> when a special condition occurs a sort on another key should be performed?
> 
> For example, [[1,2], [2, 2], [3, 2], [4, 0]] would be sorted, in my
> example as, [[4, 0], [3, 2], [2, 2], [1, 2]]. That is, sort on the second
> value and in case they are equal, reverse sort on the first value.
> 
> I tried doing this using sorted and using a custom cmp function but not
> sure about how to define the cmp function.

Python's list.sort() is "stable", it doesn't change the order of items that 
compare equal. Therefore you can achieve your goal by sorting twice:

>>> items = [[1,2], [2, 2], [3, 2], [0, 0]]
>>> items.sort(key=itemgetter(0), reverse=True)
>>> items
[[3, 2], [2, 2], [1, 2], [0, 0]]
>>> items.sort(key=itemgetter(1))
>>> items
[[0, 0], [3, 2], [2, 2], [1, 2]]

(I changed your last item to [0, 0] to allow me to demonstrate that two 
sorts are indeed necessary)

Using a more complex key is also possible,

>>> sorted([[1,2], [2, 2], [3, 2], [0, 0]], key=lambda item: (item[1], -
item[0]))
[[0, 0], [3, 2], [2, 2], [1, 2]]

but I think that is less elegant.


From tvssarma.omega9 at gmail.com  Mon Jan  9 14:09:26 2012
From: tvssarma.omega9 at gmail.com (Sarma Tangirala)
Date: Mon, 9 Jan 2012 18:39:26 +0530
Subject: [Tutor] Sorting Nested Lists
In-Reply-To: <4F0AE3F6.7020508@pearwood.info>
References: <CABFCkKSci2f_rKztdhqtQecsqc1D3N-katx2Ns9WLF3D5hwVkA@mail.gmail.com>
	<4F0AE3F6.7020508@pearwood.info>
Message-ID: <CABFCkKS5dLfKfGtapbm3Lp30biGtN8=R9uXBQTaaJ89p1QV4ig@mail.gmail.com>

On 9 January 2012 18:26, Steven D'Aprano <steve at pearwood.info> wrote:

> Sarma Tangirala wrote:
>
>> Hi list,
>>
>> I was banging my head about a pythonic way of doing the following,
>>
>> Given a nested list, how do I sort the uppermost list based on one key and
>> when a special condition occurs a sort on another key should be performed?
>> For example, [[1,2], [2, 2], [3, 2], [4, 0]] would be sorted, in my
>> example
>> as, [[4, 0], [3, 2], [2, 2], [1, 2]]. That is, sort on the second value
>> and
>> in case they are equal, reverse sort on the first value.
>>
>
> That is not exactly a good example. There are at least two other ways to
> get the result you show, both much more obvious:
>
> py> L = [[1,2], [2, 2], [3, 2], [4, 0]]
> py> list(reversed(L))
>
> [[4, 0], [3, 2], [2, 2], [1, 2]]
> py> sorted(L, reverse=True)
>
> [[4, 0], [3, 2], [2, 2], [1, 2]]
>
>
> If I ignore your example, and just use the description:
>
> "sort on the second value, and in case they are equal, reverse sort on the
> first value"
>
> the way to do this is with a double sort. Note that this works because
> Python's sort is stable: in the event of ties, the first item remains
> first. In earlier versions of Python, this was not always the case.
>
> So, given this list:
>
> L = [[1,2], [4,0], [3,2], [2,2], [5,1], [1,1]]
>
> first sort in reverse by the first item, then by the second:
>
>
> py> L.sort(key=lambda sublist: sublist[0], reverse=True)
> py> L.sort(key=lambda sublist: sublist[1])
> py> print L
> [[4, 0], [5, 1], [1, 1], [3, 2], [2, 2], [1, 2]]
>
>
>
> Note that using a key function is MUCH more efficient than a cmp function.
> Comparison functions end up doing much more work, and hence are very much
> slower, than a key function.
>
> Also note that in recent versions of Python, you can do without the lambda
> function and use the special "itemgetter" function:
>
>
> py> from operator import itemgetter
> py> L = [[1,2], [4,0], [3,2], [2,2], [5,1], [1,1]]
> py> L.sort(key=itemgetter(0), reverse=True)
> py> L.sort(key=itemgetter(1))
> py> print L
> [[4, 0], [5, 1], [1, 1], [3, 2], [2, 2], [1, 2]]
>
>
I tried this a lot yesterday but seemed to get a wrong answer but now I
realize its because of a bad test case. Thank you.


>
> Last but not least, I will show how to do it using a custom cmp function.
> But I recommend that you don't use this!
>
> def my_cmp(list1, list2):
>    x = cmp(list1[1], list2[1])
>    if x == 0:  # a tie
>        x = cmp(list2[0], list1[0])  # swap the order for reverse sort
>        # or if you prefer, x = -cmp(list1[0], list2[0])
>    return x
>
> sorted(L, my_cmp)
>
>
>
>
> --
> Steven
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>



-- 
Sarma Tangirala,
Class of 2012,
Department of Information Science and Technology,
College of Engineering Guindy - Anna University
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120109/46192bf3/attachment-0001.html>

From wprins at gmail.com  Mon Jan  9 14:18:36 2012
From: wprins at gmail.com (Walter Prins)
Date: Mon, 9 Jan 2012 13:18:36 +0000
Subject: [Tutor] Sorting Nested Lists
In-Reply-To: <CABFCkKSci2f_rKztdhqtQecsqc1D3N-katx2Ns9WLF3D5hwVkA@mail.gmail.com>
References: <CABFCkKSci2f_rKztdhqtQecsqc1D3N-katx2Ns9WLF3D5hwVkA@mail.gmail.com>
Message-ID: <CANLXbfCQwxjXxgB+j7G3RQzB6rHd7pYuTKnCwuw6yMFQ2DKM-Q@mail.gmail.com>

Hi,

On 9 January 2012 12:31, Sarma Tangirala <tvssarma.omega9 at gmail.com> wrote:
> Given a nested list, how do I sort the uppermost list based on one key and
> when a special condition occurs a sort on another key should be performed?
>
> For example, [[1,2], [2, 2], [3, 2], [4, 0]] would be sorted, in my example
> as, [[4, 0], [3, 2], [2, 2], [1, 2]]. That is, sort on the second value and
> in case they are equal, reverse sort on the first value.
>
> I tried doing this using sorted and using a custom cmp function but not sure
> about how to define the cmp function.

See the following page (particularly the section that describes
"multiple levels of sorting") for how to do (I think) what you want
(though this does not use the compare function):
http://wiki.python.org/moin/HowTo/Sorting

If you really want to have this done via the compare function method
then post back again.

Walter

From jeanpierreda at gmail.com  Mon Jan  9 14:39:53 2012
From: jeanpierreda at gmail.com (Devin Jeanpierre)
Date: Mon, 9 Jan 2012 08:39:53 -0500
Subject: [Tutor] making a custom file parser?
In-Reply-To: <CAJmBOfn-DBXdYsSC1=h3snbK1mL8XCFzeARvOzOnMMJzXhSnUQ@mail.gmail.com>
References: <CAF=P20UoF7Fn5W+qnpO1rASQVJbYKDQ0sBC9-rpWm3Hvhit7Tg@mail.gmail.com>
	<201201071301.21959.cfuller084@thinkingplanet.net>
	<CAF=P20XjYM1C0XycnWKFHwg8SRgPNJ8k8Eduk=SAj9NCazYbVA@mail.gmail.com>
	<CAJmBOf=9dcrR=iw3-04vUtH0ND4Smf2H92vpTvks8mvPkDQxkw@mail.gmail.com>
	<CABicbJKVWR7bo9fQ3W91VMZ4sXtB62kp6WTQ2PV-fO7nwMjCow@mail.gmail.com>
	<CAJmBOfn-DBXdYsSC1=h3snbK1mL8XCFzeARvOzOnMMJzXhSnUQ@mail.gmail.com>
Message-ID: <CABicbJKxeT-xYNz7UvH2h79ffvyOgaRZ8w604Ao2aEseOO12fg@mail.gmail.com>

> IIRC, Python's only non-regular feature is backreferences though

Probably. I'm not too familiar with a couple other features or how
their semantics work, in particular the (?(id)yes|no) syntax.

> I'm not calling bs or anything, I don't know anything about .net
> regexes and I'll readily believe it can be done (I just want to see
> the code for myself).

They add the ability to push and pop from a stack, which turns their
regular expressions into at-least-as-powerful as push-down automata,
which are equivalent in power to context-free-grammars, which means
they can match XML. I think this has been well-known in the .NET
community for years, but nobody had ever done it, and nobody ever
mentioned it. It's a dirty secret you don't tell the newbies because
then they think regexps are fine to use for everything.

It's also why I don't like the "this isn't regular so don't use
regular expressions" spiel. We call things regular expressions even
when they're context-free parsing expressions! The term has meaning,
but it's no longer tied to finite state automata, and any argument
along that lines is just waiting to be broken by the next feature
addition to the re module.

Anyway, I found the reference I was thinking of:
http://porg.es/blog/so-it-turns-out-that-dot-nets-regex-are-more-powerful-than-i-originally-thought

> Quite right. We haven't seen enough of it to be sure, but that little
> bite seems parseable enough with some basic string methods and one or
> two regexes. That's really all you need, and trying to do the whole
> thing with pure regex is just needlessly overcomplicating things (I'm
> pretty sure we all actually agree on that).

Oh I dunno. If the regex would be simple, it'd be the simplest
solution. As soon as you have order-independence though...

> You mean like flex/bison? May be overkill, but then again, maybe not.
> So much depends on the data.

Flex/Bison are a little old-school / difficult to deal with. I'm more
thinking LEPL or PyMeta or something.

-- Devin

On Sun, Jan 8, 2012 at 9:06 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote:
> On Mon, Jan 9, 2012 at 2:19 AM, Devin Jeanpierre <jeanpierreda at gmail.com> wrote:
>>> Parsing XML with regular expressions is generally very bad idea. In
>>> the general case, it's actually impossible. XML is not what is called
>>> a regular language, and therefore cannot be parsed with regular
>>> expressions. You can use regular expressions to grab a limited amount
>>> of data from a limited set of XML files, but this is dangerous, hard,
>>> and error-prone.
>>
>> Python regexes aren't regular, and this isn't XML.
>>
>> A working XML parser has been written using .NET regexes (sorry, no
>> citation -- can't find it), and they only have one extra feature
>> (recursion, of course). And it was dreadfully ugly and nasty and
>> probably terrible to maintain -- that's the real cost of regexes.
>>
>
> IIRC, Python's only non-regular feature is backreferences though; I'm
> pretty sure that isn't enough to parse XML. It does not make it
> powerful enough to parse context-free languages. I really would like
> that citation though, tried googling for it but not much turned up.
> I'm not calling bs or anything, I don't know anything about .net
> regexes and I'll readily believe it can be done (I just want to see
> the code for myself). But really I still wouldn't dare try without a
> feature set like perl 6's regexes. And even then..
>
> You're technically correct (it's the best kind), but I feel like it
> doesn't really take away the general correctness of my advice ;)
>
>> In particular, his data actually does look regular.
>>
>
> Quite right. We haven't seen enough of it to be sure, but that little
> bite seems parseable enough with some basic string methods and one or
> two regexes. That's really all you need, and trying to do the whole
> thing with pure regex is just needlessly overcomplicating things (I'm
> pretty sure we all actually agree on that).
>
>>> I'll assume that said "(.*)". There's still a few problems: < and >
>>> shouldn't be escaped, which is why you're not getting any matches.
>>> Also you shouldn't use * because it is greedy, matching as much as
>>> possible. So it would match everything in between the first <unit> and
>>> the last </unit> tag in the file, including other <unit></unit> tags
>>> that might show up.
>>
>> On the "can you do work with this with regexes" angle: if units can be
>> nested, then neither greedy nor non-greedy matching will work. That's
>> a particular case where regular expressions can't work for your data.
>>
>>> Test it carefully, ditch elementtree, use as little regexes as
>>> possible (string functions are your friends! startswith, split, strip,
>>> et cetera) and you might end up with something that is only slightly
>>> ugly and mostly works. That said, I'd still advise against it. turning
>>> the files into valid XML and then using whatever XML parser you fancy
>>> will probably be easier.
>>
>> He'd probably do that using regexes.
>>
>
> Yeah, that's what I was thinking when I said it too. Something like,
> one regex to quote attributes, and one that adds close tags at the
> earliest opportunity. Like right before a newline? It looks okay based
> on just that sample, but it's really hard to say. The viability of
> regexes depends so much on the dataset you have. If you can make the
> dataset valid XML with just three regexes (quotes, end tags, comments)
> then just parse it that way, that sounds like the simplest possible
> option.
>
>> Easiest way is probably to write a real parser using some PEG or CFG
>> thingy. Less error-prone.
>>
>
> You mean like flex/bison? May be overkill, but then again, maybe not.
> So much depends on the data.
>
>> Overall agree with advice, though. Just being picky. Sorry.
>>
>> -- Devin
>>
>>
>
> I love being picky myself, so I don't mind, as long as there is a
> disclaimer somewhere ;) Cheers,
> Hugo

From msg.ufo at gmail.com  Mon Jan  9 19:31:44 2012
From: msg.ufo at gmail.com (Mike G)
Date: Mon, 9 Jan 2012 10:31:44 -0800
Subject: [Tutor]  Moving from snippits to large projects?
Message-ID: <CAHD43mr3TEPYJSFCjSXgL7=WCAhYt37hpWop7qXWN-d2qR7D4g@mail.gmail.com>

<quote> How does one go from small to medium, to large, as a coder? </quote>

You might look into contributing to an existing project.

There is a new project, MediaLocker, a Python / wxPython app recently
underway, started from a blog post. I
believe they are looking for input, including contributing - have a look.

http://www.medialocker.pythonlibrary.org/

From leamhall at gmail.com  Mon Jan  9 20:00:41 2012
From: leamhall at gmail.com (leam hall)
Date: Mon, 9 Jan 2012 14:00:41 -0500
Subject: [Tutor] Moving from snippits to large projects?
In-Reply-To: <CAHD43mr3TEPYJSFCjSXgL7=WCAhYt37hpWop7qXWN-d2qR7D4g@mail.gmail.com>
References: <CAHD43mr3TEPYJSFCjSXgL7=WCAhYt37hpWop7qXWN-d2qR7D4g@mail.gmail.com>
Message-ID: <CACv9p5pKaL+eUmRM5_RYBVmHeY+wvyJ6svK5FX4ut=QowZMsYg@mail.gmail.com>

On 1/9/12, Mike G <msg.ufo at gmail.com> wrote:
> <quote> How does one go from small to medium, to large, as a coder? </quote>
>
> You might look into contributing to an existing project.
>
> There is a new project, MediaLocker, a Python / wxPython app recently
> underway, started from a blog post. I
> believe they are looking for input, including contributing - have a look.
>
> http://www.medialocker.pythonlibrary.org/

Mike,

Media locker looks interesting, thanks!

Leam


-- 
Mind on a Mission <http://leamhall.blogspot.com/>

From jeffpeery at yahoo.com  Mon Jan  9 23:02:09 2012
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Mon, 9 Jan 2012 14:02:09 -0800 (PST)
Subject: [Tutor] USB volume unique volume info
Message-ID: <1326146529.21080.YahooMailNeo@web43138.mail.sp1.yahoo.com>

Hello,
I am writing a python script to install a program onto a customer computer from a USB drive. To prevent piracy, I want to know if the user has copied my install program to another USB drive. Do USB drives have some unique volume info or another feature that I might query to detect if the program is still operating on the original USB drive?

Thanks,
Jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120109/3171d1db/attachment.html>

From defensoft at gmail.com  Wed Jan  4 21:45:58 2012
From: defensoft at gmail.com (Nate Lastname)
Date: Wed, 4 Jan 2012 15:45:58 -0500
Subject: [Tutor] Help with lag
Message-ID: <CABe2FwoFExtL7rEGAyg1=D+_OMPX6n7y9zMJ=FpFynMFTKGgkA@mail.gmail.com>

Hello!

The attached file 'cameramovement.py' is very laggy. Could someone help me
out by telling me what part of this is slowing it down so much?  I've
checked the whole file through, and I can't see why it's so slow. You'll
have to place the pngs and bmps in the folder data/test, and the other pys
in the same folder with cameramovement. Thanks!

Thanks
-Defenestrator.


P.S. - I know that the load time is long.  That is not the problem I have.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120104/ffba1a5f/attachment-0001.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: basics.py
Type: application/octet-stream
Size: 3399 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120104/ffba1a5f/attachment-0003.obj>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: cameramovement.py
Type: application/octet-stream
Size: 3009 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120104/ffba1a5f/attachment-0004.obj>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: platformchar.py
Type: application/octet-stream
Size: 6536 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120104/ffba1a5f/attachment-0005.obj>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: tile.png
Type: image/png
Size: 906 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120104/ffba1a5f/attachment-0002.png>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: map2.bmp
Type: image/bmp
Size: 41078 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120104/ffba1a5f/attachment-0002.bin>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: map.bmp
Type: image/bmp
Size: 2278 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120104/ffba1a5f/attachment-0003.bin>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: playa.png
Type: image/png
Size: 287 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120104/ffba1a5f/attachment-0003.png>

From japhy at pearachute.com  Fri Jan  6 06:08:06 2012
From: japhy at pearachute.com (Japhy Bartlett)
Date: Thu, 5 Jan 2012 23:08:06 -0600
Subject: [Tutor] Game lag
In-Reply-To: <CABe2Fwoy4rRy7dz=TOHdUyDWY3Z1q1Q4UN2-sHcAkCre4AhFSw@mail.gmail.com>
References: <CABe2Fwp4UEGM9NWje2FFR2rXqCh=ZirNVSChH-D_Nh4rgMf6-Q@mail.gmail.com>
	<CAJmBOfmP80nXiF+fk84zsTfBu8c9Z+12=S4hCiXpodif9kZmgQ@mail.gmail.com>
	<CABe2Fwoy4rRy7dz=TOHdUyDWY3Z1q1Q4UN2-sHcAkCre4AhFSw@mail.gmail.com>
Message-ID: <4608D8C1-89DC-43F1-8B69-5DCACD5FCCC4@pearachute.com>

If you made an effort to strip out parts of your code, it would  
probably show you where the bottlenecks are.

You say that the large map is not the problem, but do you really know?


On Jan 5, 2012, at 10:08 AM, Nate Lastname <defensoft at gmail.com> wrote:

> Thanks for the profilers - never had hear of 'em. Also, no, I cannot  
> strip out unnecessary parts, 'cuz I don't know what part is slowing  
> it down.  Thanks a lot, though Hugo.
>
> On Thu, Jan 5, 2012 at 11:02 AM, Hugo Arts <hugo.yoshi at gmail.com>  
> wrote:
> On Thu, Jan 5, 2012 at 3:56 PM, Nate Lastname <defensoft at gmail.com>  
> wrote:
> > Hello all,
> >
> > The attached zip file contains a file called 'cameramovement.py'.   
> As you
> > can see, this file is extremely laggy.  After searching through my  
> code, I
> > can't find anything that is slowing it down.  Could someone help  
> me out?  It
> > takes a while to load due to a large map.  This is not the problem.
> >
> > Thanks,
> > The Defenestrator
> >
> > P.S. Yes, I am new here.  Hello, all!
> >
>
> 1) although posting here is a good idea, you're gonna be better off
> asking the pygame mailing list about this as well, they're the experts
> 2) that's a lot of code for me to read all in my spare time man, isn't
> there any way you can simplify it or strip out unnecessary parts?
> 3) did you profile it? Do this! Now! rather than guess where your code
> is slow, this will tell you exactly. Use cProfile:
>
> http://docs.python.org/library/profile.html
>
> HTH,
> Hugo
>
>
>
> -- 
> My Blog - Defenestration Coding
>
> http://defenestrationcoding.wordpress.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/20120105/21df2ea9/attachment-0001.html>

From varsha.purohit at gmail.com  Sat Jan  7 02:08:54 2012
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Fri, 6 Jan 2012 17:08:54 -0800
Subject: [Tutor] Removing certain sequences from a string list elements
Message-ID: <CAMe-Gs-d96hEmo-29CmNJwUEP+yh4Tsu4mEZEW-tMPjNu+1i2A@mail.gmail.com>

Hello,

I have a simple python program where I am comparing two log files and I am
storing the differences in a list. I am programming in python after a long
time so may be I might have not written something very efficient. Please
let me know what alternate solution I can apply for my program.

I am reading each line in the file individually and storing them in a list.
After that i am comparing the two lists and printing out the differences.
But I wanted to know how can I iter through each string in the list and
remove certain sequences like \n and ',' comma. I want to basically
printout a column where it has each element of the list in each row.
It should also avoid priting the time stamp since they will be different
anyway. i want the program as simple as it looks right now.

Input file contains something like this in each line. I have not included
the complete log file.

*MegaMon> mfc*
*MFC data:*
*    vendorId/deviceId=1000/005b, subVendorId/subDeviceId=1000/9285, OEM=1,
SubOem=1, isRaidKeySecondary=0*
*    MFCF: disableSAS=0, maxDisks=0, enableRaid6=1, disableWideCache=0*
*    disableRaid5=0, enableSecurity=0, enableReducedFeatureSet=0*
*    enableCTIO=0 enableSnapshot=1 enableSSC=1 enableCacheOffload=0*
*    maxHANodes=2*


here is the program

def readList1():
    f1 = open('mfc_node1.txt',"r")
    lines = f1.read().split(" ")
    q = []
    for line in lines:
        if not line in q:
            q.append(line)
    f1.close()
    return q

def readList2():
    f = open('mfc_node2.txt',"r")
    lines = f.read().split(" ")
    p = []
    for line in lines:
        if not line in p:
            p.append(line)
    f.close()
    return p



if __name__ == "__main__":
    q = readList1()
    #print q
    p = readList2()
    #print p
    newList = []

    for x in q:
        if x not in p:
            newList.append(x)


Here is the part of the output list
['enableCTIO=0,', 'enableSnapshot=1,', 'enableSSC=1,', 'maxHANodes=0\n',
'sasAddr=5123456712345678\nSecondary', 'enableSnapshot=0,', 'enableSSC=0,',
'sasAddr=0000000000000000\nMegaMon>', '13:53:14:']

-Varsha
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120106/4e293a4c/attachment-0001.html>

From cfuller at thinkingplanet.net  Sat Jan  7 06:16:51 2012
From: cfuller at thinkingplanet.net (Chris Fuller)
Date: Fri, 6 Jan 2012 23:16:51 -0600
Subject: [Tutor] Subclassing Exceptions
In-Reply-To: <4F07D080.8080600@pearwood.info>
References: <201201062124.41384.cfuller084@thinkingplanet.net>
	<4F07D080.8080600@pearwood.info>
Message-ID: <201201062316.51767.cfuller@thinkingplanet.net>

On Friday 06 January 2012, Steven D'Aprano wrote:
> Chris Fuller wrote:
> >>>> class Foo(SyntaxError):
> > ...  def __init__(self, a,b,c):
> > ...   self.args = (a,b,c)
> > ...
> > 
> >>>> raise Foo(1,2,3)
> > 
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in <module>
> > 
> > __main__.Foo: None
> > 
> > 
> > Inheriting from SyntaxError doesn't work!  When I create a new exception,
> > I generally subclass from the built-in exception it most resembles, in
> > case there was some reason to also catch it via an ancestor.  But I'm
> > not sure if that is really all that useful an idea in practice.  How do
> > you folk do it?
> 
> What do you mean, "doesn't work"? It looks like it works to me. You get a
> Foo exception, exactly as expected. The error message isn't what you
> expect, because you're making unwarranted assumptions about SyntaxError
> and how it works.
> 
> In general, when you override a method, you take full responsibility to
> perform everything that the superclass method was supposed to do. In this
> case, you fail to assign to msg as well as args. It is safer to overload a
> 
> message rather than override it:
>  >>> class Spam(SyntaxError):
> ...     def __init__(self, *args):
> ...             if args:
> ...                     args  = ("I pity the fool who made a mistake",) +
> args[1:] ...             super(Spam, self).__init__(*args)
> ...
> 
>  >>> raise Spam('you made a mistake', 1, 2)
> 
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> __main__.Spam: I pity the fool who made a mistake
> 
> 
> 
> Unfortunately, there's no real consistency in what arguments exceptions are
> expected to take. The best thing is to read the docs, if they have any, or
> use introspection and trial and error to work out what they do.
> 
>  >>> try:
> ...     raise SyntaxError("you made a mistake")
> ... except SyntaxError, err:
> ...     pass
> ...
> 
>  >>> err.msg
> 
> 'you made a mistake'
> 
> 
> See dir(err) for more; you can use help(SyntaxError) but unfortunately it
> isn't very useful.
> 
> 
> You probably shouldn't inherit from SyntaxError, since it represents syntax
> errors in the Python code being interpreted or compiled. Any syntax error
> in your own data structures should be independent of SyntaxError.

In "Python: Essential Reference", David Beazley recommends that the parameters 
of the exception be assigned to the args attribute, so it is passed all the 
way through the traceback.  You will observe that the last element in the 
traceback loses this information when subclassed from SyntaxError.  This isn't 
a problem when the whole traceback is laid out before you, but can come into 
play with automated tools that catch/log/manipulate exceptions.  This behavior 
of exceptions isn't apparently mentioned in the canonical documentation, 
however.

I had the same thought about not wanting to mix syntax errors in the data with 
syntax errors in the code, but that applies to any exception, really.  In 
fact, it's better to inherit from a more derived class, because when you catch 
an ancestor, you'll be grabbing less greedily at the possible coding errors.  
Which suggests that giving a damn about built-in ancestors of user-defined 
exceptions is a losing proposition, now that I think about it.

Cheers

From oldcowboyrocky at gmail.com  Mon Jan  9 00:53:17 2012
From: oldcowboyrocky at gmail.com (emin)
Date: Sun, 8 Jan 2012 15:53:17 -0800
Subject: [Tutor] x%2
Message-ID: <08EE20443EDD47C4BA5C0E843927DA26@workstation>

http://www.youtube.com/watch?src_vid=QaYAOR4Jq2E&feature=iv&annotation_id=annotation_149056&v=M3g1GEkmyrw
in this tutorial what does mean x%2 ?
i think: i * 2% = always even number 
but why not 4,6 or 8? but  i * 4(6,8,10,12...)% = always even number too
for example: 100 * 2(4,6,8,10,12...)% = 2(4,6,8,10,12...)
even numbers = {2,4,6,8,10,12...}
and how pyton understanding 0(even or odd number or it is an exception?)?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120108/6d6f0177/attachment-0001.html>

From enalicho at gmail.com  Tue Jan 10 02:13:24 2012
From: enalicho at gmail.com (Noah Hall)
Date: Tue, 10 Jan 2012 01:13:24 +0000
Subject: [Tutor] x%2
In-Reply-To: <08EE20443EDD47C4BA5C0E843927DA26@workstation>
References: <08EE20443EDD47C4BA5C0E843927DA26@workstation>
Message-ID: <CAOv69sZEWXcxJqdTA=hP606F-3wbRraeUZcE+K6A8486n9L+PA@mail.gmail.com>

2012/1/8 emin <oldcowboyrocky at gmail.com>:
> http://www.youtube.com/watch?src_vid=QaYAOR4Jq2E&feature=iv&annotation_id=annotation_149056&v=M3g1GEkmyrw
> in this tutorial what does mean x%2 ?
> i think: i * 2% = always even number
> but why not 4,6 or 8? but? i * 4(6,8,10,12...)% = always even number too
> for example: 100 * 2(4,6,8,10,12...)% = 2(4,6,8,10,12...)
> even numbers = {2,4,6,8,10,12...}
> and how pyton understanding 0(even or odd number or it is an exception?)?

While it is true that all numbers divisible by 4 are even, not all
even numbers are divisible by 4. All even numbers, however, are
divisible by 2.

From steve at pearwood.info  Tue Jan 10 03:23:02 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 10 Jan 2012 13:23:02 +1100
Subject: [Tutor] x%2
In-Reply-To: <08EE20443EDD47C4BA5C0E843927DA26@workstation>
References: <08EE20443EDD47C4BA5C0E843927DA26@workstation>
Message-ID: <4F0BA106.2060009@pearwood.info>

emin wrote:
> http://www.youtube.com/watch?src_vid=QaYAOR4Jq2E&feature=iv&annotation_id=annotation_149056&v=M3g1GEkmyrw
> in this tutorial what does mean x%2 ?

x % 2 gives the remainder when you divide x by 2.

> i think: i * 2% = always even number 

What does that mean? i*2% does not work in Python. In Python, % does not mean 
percentage and so you can't multiply by 2%.

I guess you mean

     i % 2 == 0 means i is an even number

and this would be correct. If i % 2 == 0 then i is even. If it equals 1 then i 
is odd.

> but why not 4,6 or 8? but  i * 4(6,8,10,12...)% = always even number too

The remainder i % n will be a number between 0 and n-1. i%2 is useful because 
there are only two possible results, 0 (i is even) or 1 (i is odd).

i%4 is less useful, because there are four possibilities:

0 (i is even)
1 (i is odd)
2 (i is even)
3 (i is odd)

i%10 is less useful still, because there are ten possibilities:

0,2,4,6,8: i is even
1,3,5,7,9: i is odd


> for example: 100 * 2(4,6,8,10,12...)% = 2(4,6,8,10,12...)
> even numbers = {2,4,6,8,10,12...}

I don't understand what you are trying to say here.


> and how pyton understanding 0(even or odd number or it is an exception?)?

0 is always an even number, because it has 0 remainder when you divide by 2.



-- 
Steven

From steve at pearwood.info  Tue Jan 10 03:28:08 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 10 Jan 2012 13:28:08 +1100
Subject: [Tutor] USB volume unique volume info
In-Reply-To: <1326146529.21080.YahooMailNeo@web43138.mail.sp1.yahoo.com>
References: <1326146529.21080.YahooMailNeo@web43138.mail.sp1.yahoo.com>
Message-ID: <4F0BA238.9000901@pearwood.info>

Jeff Peery wrote:
> Hello, I am writing a python script to install a program onto a customer
> computer from a USB drive. To prevent piracy, I want to know if the user
> has copied my install program to another USB drive. Do USB drives have some
> unique volume info or another feature that I might query to detect if the
> program is still operating on the original USB drive?


I'm sorry, this is a mailing list about learning the Python programming 
language, not about the minutia of technical details about USB drives. Have 
you tried googling for "USB drive unique identifier"?

https://duckduckgo.com/html/?q=usb%20drive%20unique%20identifier



-- 
Steven

From tonyelle1 at sbcglobal.net  Tue Jan 10 09:38:18 2012
From: tonyelle1 at sbcglobal.net (tonyelle)
Date: Tue, 10 Jan 2012 00:38:18 -0800 (PST)
Subject: [Tutor] Issue with Python 2.7.2 - beginner needing help
Message-ID: <1326184698.22228.YahooMailClassic@web181405.mail.ne1.yahoo.com>

Hello!
I am just beginning to learn Python from the book Starting Out With Python - 2nd Edition. ?I have read and completed exercises up to page 45. I am currently learning how to display multiple items with one call to the print function.?? ? ? ?ex:?1 # This program demonstrates a variable.
? ? ? ? ? ?2 room = 503
? ? ? ? ? ?3 print('I am staying in room number', room)

? ? ? ? ? ?Program Output:
? ? ? ? ? ?I am staying in room number 503
However, when I type this out exactly as shown, my program output looks very similar to line 3.
? ? ? ? ?My program output should look like: ? I am staying in room number 503? ? ? ? ?BUT, it looks like this: ?('I am staying in room number', 503)?
How can this be fixed? ?I need help and can't find any information when I search the web. ?I don't know if this is a problem that can be fixed or if it is a problem at all.?
I know I have a limited Python vocabulary and it may be hard to understand my question. I tried to explain as clearly as possible. If you can understand my issue and have the time to answer my question, I would greatly appreciate it. I would rather not continue my lessons until this is resolved.?
Sincerely,?Tonyelle Evans

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

From msg.ufo at gmail.com  Tue Jan 10 10:14:01 2012
From: msg.ufo at gmail.com (Mike G)
Date: Tue, 10 Jan 2012 01:14:01 -0800
Subject: [Tutor]  Issue with Python 2.7.2 - beginner needing help
Message-ID: <CAHD43mq7tAyd-Rs-iXSM5ZT5y+6mZ9hDuHV02Uz5oTVyAP3ovw@mail.gmail.com>

Hi Tonyelle

Your code doesn't work as expected due to your 2nd edition book uses
Python 3x, see page xi, 'Changes in this edition'.

This would work for your version of Python...

room = 503
print 'I am staying in room number', room

If you're new, Python 2.7.2 is (IMO) a better choice, many more
tutorials, books etc available as resources, including Gaddis's 1st
edition 'Starting Out with Python' which uses Python 2x.

From antonijevic.b at gmail.com  Tue Jan 10 11:04:45 2012
From: antonijevic.b at gmail.com (Bojan Antonijevic)
Date: Tue, 10 Jan 2012 11:04:45 +0100
Subject: [Tutor] Python problem
Message-ID: <CAG0Daf=zRaBq66kwL4w4refhidupQOfzbVdCHMLrqOtKvDzMiw@mail.gmail.com>

Hello,

I send you a mail at 29.12.2011. about problem with my IDLE (Python GUI)
and I didnt recive any ansfer; Instead, I am receiving  correspondence
between other members of forum; Honestly, I don't want to receive all this
conversation's.
Thank you.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120110/bfe9aa50/attachment.html>

From wolfrage8765 at gmail.com  Tue Jan 10 11:12:50 2012
From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com)
Date: Tue, 10 Jan 2012 11:12:50 +0100
Subject: [Tutor] Python problem
In-Reply-To: <CAG0Daf=zRaBq66kwL4w4refhidupQOfzbVdCHMLrqOtKvDzMiw@mail.gmail.com>
References: <CAG0Daf=zRaBq66kwL4w4refhidupQOfzbVdCHMLrqOtKvDzMiw@mail.gmail.com>
Message-ID: <CAOhNYvkUt53n=b2dfMMRDv74TxVORP97kcs9n6KuFS+1kCb+jg@mail.gmail.com>

To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

On Tue, Jan 10, 2012 at 11:04 AM, Bojan Antonijevic
<antonijevic.b at gmail.com> wrote:
> Hello,
>
> I send you a mail at 29.12.2011. about problem with my IDLE (Python GUI) and
> I didnt recive any ansfer; Instead, I am receiving? correspondence between
> other members of forum; Honestly, I don't want to receive all this
> conversation's.
> Thank you.
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From jiaxiaolei19871112 at gmail.com  Tue Jan 10 11:25:36 2012
From: jiaxiaolei19871112 at gmail.com (=?UTF-8?B?6LS+5pmT56OK?=)
Date: Tue, 10 Jan 2012 18:25:36 +0800
Subject: [Tutor] a question about MySQLdb in python
Message-ID: <CABtGFNPjOm=hPqbwegk6FWoF6ojdCP-_=bYfCk1oK4rLSu6_qA@mail.gmail.com>

hi, all:

 python's version:  2.6.
 MySQLdb version: 1.2.3.

I once encounter with a question like this:
File
"/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3-py2.6-linux-x86_64.egg/MySQLdb/connections.py",

line 36, in defaulterrorhandler
    raise errorclass, errorvalue
OperationalError: (2006, 'MySQL server has gone away')

and i try to find the exception is how to perform to us in the source code.

when i read the source code, some questions puzzled me!

question 1? how to find the words "2006, 'MySQL server has gone away" in
sourced code?
question 2:  in MySQLdb/cursors.py , the method errorhandler() just receive
two parameters such as exc,value when it's be invoked. however, in
MySQLdb/connection.py, we define it as one receives 4 parameters such
connection, cursor, erorclass, errorvalue
                  a method should accepts 4 parameters is invoked by 2
parameters. how to explain it?
question 3: in MySQLdb/connection.py,  the module cursors is been imported.
 while,  In MySQLdb/cursors.py, some  methods such as errorhandler in
MySQLdb/connection.py is been invoked.
                the two module, which one is execute first?  which one is
added to mem first?


some important codes are shown as follows.

any response will be welcome!

-- Jia Xiaolei

-----------------------------------------------------------------------------------
 source code about MySQLdb
------------------------------------------------------
# MySQLdb/connections.py

import cursors

def defaulterrorhandler(connection, cursor, errorclass, errorvalue):
    """

    If cursor is not None, (errorclass, errorvalue) is appended to
    cursor.messages; otherwise it is appended to
    connection.messages. Then errorclass is raised with errorvalue as
    the value.

    You can override this with your own error handler by assigning it
    to the instance.

    """
    error = errorclass, errorvalue
    if cursor:
        cursor.messages.append(error)
    else:
        connection.messages.append(error)
    del cursor
    del connection
    raise errorclass, errorvalue

class Connection(_mysql.connection):

    """MySQL Database Connection Object"""

    default_cursor = cursors.Cursor
    errorhandler = defaulterrorhandler

    def __init__(self, *args, **kwargs):
         # some codes
         self.cursorclass = kwargs2.pop('cursorclass', self.default_cursor)
        charset = kwargs2.pop('charset', '')

     def cursor(self, cursorclass=None):
        """

        Create a cursor on which queries may be performed. The
        optional cursorclass parameter is used to create the
        Cursor. By default, self.cursorclass=cursors.Cursor is
        used.

        """
        return (cursorclass or self.cursorclass)(self)

    def xx(yy):
         # some codes


 # MySQLdb/cursors.py

class BaseCursor(object):
    def __init__(self, connection):
        from weakref import proxy

        self.connection = proxy(connection)
        self.description = None
        self.description_flags = None
        self.rowcount = -1
        self.arraysize = 1
        self._executed = None
        self.lastrowid = None
        self.messages = []
        self.errorhandler = connection.errorhandler
        self._result = None
        self._warnings = 0
        self._info = None
        self.rownumber = None

    def execute(self, query, args=None):

        """Execute a query.

        query -- string, query to execute on server
        args -- optional sequence or mapping, parameters to use with query.

        Note: If args is a sequence, then %s must be used as the
        parameter placeholder in the query. If a mapping is used,
        %(key)s must be used as the placeholder.

        Returns long integer rows affected, if any

        """
        from types import ListType, TupleType
        from sys import exc_info
        del self.messages[:]
        db = self._get_db()
        charset = db.character_set_name()
        if isinstance(query, unicode):
            query = query.encode(charset)
        if args is not None:
            query = query % db.literal(args)
        try:
            r = self._query(query)
        except TypeError, m:
            if m.args[0] in ("not enough arguments for format string",
                             "not all arguments converted"):
                self.messages.append((ProgrammingError, m.args[0]))
                self.errorhandler(self, ProgrammingError, m.args[0])
            else:
                self.messages.append((TypeError, m))
                self.errorhandler(self, TypeError, m)
        except:
            exc, value, tb = exc_info()
            del tb
            self.messages.append((exc, value))
            self.errorhandler(self, exc, value)
        self._executed = query
        if not self._defer_warnings: self._warning_check()
        return r

    class Cursor(CursorStoreResultMixIn, CursorTupleRowsMixIn,
             BaseCursor):
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120110/160121d5/attachment.html>

From hayzer at gmail.com  Tue Jan 10 13:15:01 2012
From: hayzer at gmail.com (Thomas Maier)
Date: Tue, 10 Jan 2012 14:15:01 +0200
Subject: [Tutor]  Testing dymamically created methods
Message-ID: <CABarSbiXzOajpoeov-9bxQgLNkkzYVea6UzG+vz=67N74WYC6A@mail.gmail.com>

Hi all,

I would like to use some existing tool like py.test or nose to
run my tests, but I failed to do so.
The problem is as follow. I have tests:

### test_methods.py ###
def test_one():
    assert 1 == 1

def test_two():
    assert 1 == 1

#############

I have abstraction layer that keeps information
about this test, like method name.
It's simple JSON file.

Then I have the test runner:

### test_runner.py ###
def read_test_definition():
   """read the JSON file and returns dict with test details"""

def test_run():
   my_test_data = read_test_definition()
   import test_methods
   for testid in my_test_data:
       my_method = my_test_data[testid]
       # here the 'my_method' is equal 'test_one' or 'test_two', hope
it's clear..
       test_method = getattr(test_methods, my_method)
       test_method()

###########

This code works without py.test or nosetests. For example if I use print
instead of 'assert'.
Both py.test and nosetests failed to execute this correctly.
Or maybe they do execute it correctly, I just don't understand it..:)
They both report only single test was executed.
I would like to see test report for each method executed in 'for' loop.
Is it possible?

PS. Sorry for my ignorance, I just started to learn Python last week.

Thanks,
Thomas

From wprins at gmail.com  Tue Jan 10 14:31:23 2012
From: wprins at gmail.com (Walter Prins)
Date: Tue, 10 Jan 2012 13:31:23 +0000
Subject: [Tutor] Testing dymamically created methods
In-Reply-To: <CABarSbiXzOajpoeov-9bxQgLNkkzYVea6UzG+vz=67N74WYC6A@mail.gmail.com>
References: <CABarSbiXzOajpoeov-9bxQgLNkkzYVea6UzG+vz=67N74WYC6A@mail.gmail.com>
Message-ID: <CANLXbfDE8Z956uavwmsZ+P268VYaqGtKe6_GyNm6keF-DyxrOg@mail.gmail.com>

Hi,

On 10 January 2012 12:15, Thomas Maier <hayzer at gmail.com> wrote:
> This code works without py.test or nosetests. For example if I use print
> instead of 'assert'.
> Both py.test and nosetests failed to execute this correctly.
> Or maybe they do execute it correctly, I just don't understand it..:)
> They both report only single test was executed.
> I would like to see test report for each method executed in 'for' loop.
> Is it possible?

For nose, I *think* you can basically achieve what you want by turning
test_run() into a generator (by essentially replacing the call to the
test_method() with a suitable "yield" statement.   See here:
http://readthedocs.org/docs/nose/en/latest/writing_tests.html#test-generators

Additionally you might also look at the TestLoader functionality for
taking further control over how and where your tests are loaded, e.g.
see for example nose.loader.loadTestsFromGenerator() or
nose.loader.loadTestsFromGeneratorMethod() (or indeed all the other
methods) here:
http://readthedocs.org/docs/nose/en/latest/api/loader.html

HTH, my $0.02 worth,

Walter

From wolfrage8765 at gmail.com  Tue Jan 10 14:38:23 2012
From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com)
Date: Tue, 10 Jan 2012 14:38:23 +0100
Subject: [Tutor] Primitive Chess Clock Program Question
In-Reply-To: <je09l2$ua$1@dough.gmane.org>
References: <BF85B26B8ED7B647ACAD9C68E89DA5540D888170@HMBREXMP03.highmark.com>
	<4F037301.60800@pearwood.info> <je09l2$ua$1@dough.gmane.org>
Message-ID: <CAOhNYvkf24NoZuHhH8_ww9MbOTqeDH09++cNc1ghCTJP-7Vd4w@mail.gmail.com>

>> I assume you want to display something like this:
>>
>> Enter your next move: 0:30
SNIP
> Assuming Steven has guessed right then I think you need to use one of the
> non blocking input mechanisms like kbhit() or getch() or somesuch.
>
> Those methods are notioriously unreliable and OS specific. For example you
> may need to use curses or the Microsoft runtime module msvcrt.
I would recommend termios for unix over curses, because curses pretty
much takes over. Something like this:
http://code.activestate.com/recipes/577977-get-single-keypress/
SNIP
> label while awaiting user input is almost trivial
> (for a GUI).

I agree with Alan, a GUI toolkit makes this trivial because it can run
using events and timers. For a terminal I would recommend you use a
couple of threads. One that checks for input on getchar() and the
other thread, the main thread, that can update the display of the
prompt. You can use Queue to pass the key(s) recieved to the main
thread. Also to reduce or eliminate flicker I would also recommend you
look at sending the backspace characters to the terminal and then
replace the correct time. Something like this:
import sys

sys.stdout.write('\b')
sys.stdout.flush()

Of course that is assuming that your terminal will support \b .

On Wed, Jan 4, 2012 at 2:22 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 03/01/12 21:28, Steven D'Aprano wrote:
>
>> I assume you want to display something like this:
>>
>> Enter your next move: 0:30
>>
>> where the "0:30" is the time remaining, and is constantly updating. When
>> it hits zero, the function returns whether the user has typed anything
>> or not.
>
>
> Assuming Steven has guessed right then I think you need to use one of the
> non blocking input mechanisms like kbhit() or getch() or somesuch.
>
> Those methods are notioriously unreliable and OS specific. For example you
> may need to use curses or the Microsoft runtime module msvcrt.
>
> The general code will look like
>
> Display prompt
> while no key hit
> ? ?sleep briefly
> ? ?update time in prompt
> ? ?(using ctrl characters to delete/overwrire previouis entry)
> #when key hit
> process input.
>
> It is a non trivial problem and the details will depend on whether you use
> curses or the microsoft route.
>
> It is one of those few cases that is actually much easier to do
> in a GUI. GUIs generally make life more complex but in this case updating a
> label while awaiting user input is almost trivial
> (for a GUI).
>
> --
> Alan G
> 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 d at davea.name  Tue Jan 10 15:14:02 2012
From: d at davea.name (Dave Angel)
Date: Tue, 10 Jan 2012 09:14:02 -0500
Subject: [Tutor] Python problem
In-Reply-To: <CAG0Daf=zRaBq66kwL4w4refhidupQOfzbVdCHMLrqOtKvDzMiw@mail.gmail.com>
References: <CAG0Daf=zRaBq66kwL4w4refhidupQOfzbVdCHMLrqOtKvDzMiw@mail.gmail.com>
Message-ID: <4F0C47AA.5050006@davea.name>

On 01/10/2012 05:04 AM, Bojan Antonijevic wrote:
> Hello,
>
> I send you a mail at 29.12.2011. about problem with my IDLE (Python GUI)
> and I didnt recive any ansfer; Instead, I am receiving  correspondence
> between other members of forum; Honestly, I don't want to receive all this
> conversation's.
> Thank you.
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
I don't see any other message from you (at least not in the last 6 
months), so I can't address your IDLE question.  Either you didn't send 
it correctly, or you used some other name.

As for getting emails between various members, that's exactly what a 
mailing list is about.  Everybody who joins gets all the traffic, and 
answers what he can.  You might be surprised how much you can learn by 
reading other's questions and the replies they get.  And you also might 
be surprised how much you can learn trying to help others.

If you don't want to be bothered, then instructions for  unsubscribing 
are in every message, including this one.


-- 

DaveA


From hayzer at gmail.com  Tue Jan 10 15:37:20 2012
From: hayzer at gmail.com (Thomas Maier)
Date: Tue, 10 Jan 2012 16:37:20 +0200
Subject: [Tutor] Testing dymamically created methods
In-Reply-To: <CANLXbfDE8Z956uavwmsZ+P268VYaqGtKe6_GyNm6keF-DyxrOg@mail.gmail.com>
References: <CABarSbiXzOajpoeov-9bxQgLNkkzYVea6UzG+vz=67N74WYC6A@mail.gmail.com>
	<CANLXbfDE8Z956uavwmsZ+P268VYaqGtKe6_GyNm6keF-DyxrOg@mail.gmail.com>
Message-ID: <CABarSbhibXBVGy2jMeLJdGCD34Wn=qNhrW87_YcgJf7_dPUeDw@mail.gmail.com>

On Tue, Jan 10, 2012 at 3:31 PM, Walter Prins <wprins at gmail.com> wrote:
> Hi,
>
> On 10 January 2012 12:15, Thomas Maier <hayzer at gmail.com> wrote:
>> This code works without py.test or nosetests. For example if I use print
>> instead of 'assert'.
>> Both py.test and nosetests failed to execute this correctly.
>> Or maybe they do execute it correctly, I just don't understand it..:)
>> They both report only single test was executed.
>> I would like to see test report for each method executed in 'for' loop.
>> Is it possible?
>
> For nose, I *think* you can basically achieve what you want by turning
> test_run() into a generator (by essentially replacing the call to the
> test_method() with a suitable "yield" statement. ? See here:
> http://readthedocs.org/docs/nose/en/latest/writing_tests.html#test-generators
Works perfect.

> Additionally you might also look at the TestLoader functionality for
> taking further control over how and where your tests are loaded, e.g.
> see for example nose.loader.loadTestsFromGenerator() or
> nose.loader.loadTestsFromGeneratorMethod() (or indeed all the other
> methods) here:
> http://readthedocs.org/docs/nose/en/latest/api/loader.html
Will try later.

> HTH, my $0.02 worth,
>
> Walter

Thank you very much!

Thomas

From __peter__ at web.de  Tue Jan 10 15:40:57 2012
From: __peter__ at web.de (Peter Otten)
Date: Tue, 10 Jan 2012 15:40:57 +0100
Subject: [Tutor] a question about MySQLdb in python
References: <CABtGFNPjOm=hPqbwegk6FWoF6ojdCP-_=bYfCk1oK4rLSu6_qA@mail.gmail.com>
Message-ID: <jehilf$b1j$1@dough.gmane.org>

??? wrote:

> hi, all:
> 
>  python's version:  2.6.
>  MySQLdb version: 1.2.3.
> 
> I once encounter with a question like this:
> File
> "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3-py2.6-linux-
x86_64.egg/MySQLdb/connections.py",
> 
> line 36, in defaulterrorhandler
>     raise errorclass, errorvalue
> OperationalError: (2006, 'MySQL server has gone away')
> 
> and i try to find the exception is how to perform to us in the source
> code.
> 
> when i read the source code, some questions puzzled me!
> 
> question 1? how to find the words "2006, 'MySQL server has gone away" in
> sourced code?

The 'MySQL server has gone away' message is probably in the client part of 
MySQL's C code. If you don't want to download that wholesale you can use a 
search engine like www.koders.com to look at some candidate files.

> question 2:  in MySQLdb/cursors.py , the method errorhandler() just
> receive two parameters such as exc,value when it's be invoked. however, in
> MySQLdb/connection.py, we define it as one receives 4 parameters such
> connection, cursor, erorclass, errorvalue
>                   a method should accepts 4 parameters is invoked by 2
> parameters. how to explain it?

Consider:

def defaulterrorhandler(four, three, two, one):
    ...
class Connection:
    errorhandler = defaulterrorhandler

connection = Connection()

At this point connection.errorhandler is a "bound method", i. e. argument 
"four" is the connection instance. The method expects only three more 
arguments. Now after

class Cursor:
    def __init__(self, connection):
        self.errorhandler = connection.errorhandler
    
cursor = Cursor(connection)

cursor.errorhandler can be called with three arguments and looking at the 
quoted code that indeed happens, e. g. in the following line:

>                 self.errorhandler(self, ProgrammingError, m.args[0])

You are probably conditioned to disregard the first argument, self, because 
of its name, but it counts just as well. The Cursor instance isn't added 
automatically as the binding mechanism only kicks in when a function is 
found in the class __dict__, but errorhandler is put into the __dict__ of 
the instance.

>>> class A:
...     pass
...
>>> def f(*args): print args
...
>>> a = A()
>>> a.f = f
>>> a.f()
()
>>> A.g = f
>>> a.g()
(<__main__.A instance at 0x7f8d50e765f0>,)


> question 3: in MySQLdb/connection.py,  the module cursors is been
> imported.
>  while,  In MySQLdb/cursors.py, some  methods such as errorhandler in
> MySQLdb/connection.py is been invoked.
>                 the two module, which one is execute first?  which one is
> added to mem first?

When a module is imported the code to create its functions, classes, and 
other values is executed. The code inside the functions and methods is not 
run until a function is explicitly invoked or a class is instantiated. For 
this reason (and because of the module cache) it is even possible (though 
strongly discouraged) to have two modules import each other:

$ cat one.py
print "importing one"

import two

def f(n):
    print "one.f(%s)" % n
    if n:
        two.f(n-1)
$ cat two.py
print "importing two"

import one

def f(n):
    print "two.f(%s)" % n
    if n:
        one.f(n-1)
$ python -c 'import one; one.f(5)'
importing one
importing two
one.f(5)
two.f(4)
one.f(3)
two.f(2)
one.f(1)
two.f(0)



From hugo.yoshi at gmail.com  Tue Jan 10 17:07:32 2012
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Tue, 10 Jan 2012 17:07:32 +0100
Subject: [Tutor] Help with lag
In-Reply-To: <CABe2FwoFExtL7rEGAyg1=D+_OMPX6n7y9zMJ=FpFynMFTKGgkA@mail.gmail.com>
References: <CABe2FwoFExtL7rEGAyg1=D+_OMPX6n7y9zMJ=FpFynMFTKGgkA@mail.gmail.com>
Message-ID: <CAJmBOfnHstqkxgu0uZwzC3m_QyQHjLtJw25Crz0GetbPFSm1AA@mail.gmail.com>

On Wed, Jan 4, 2012 at 9:45 PM, Nate Lastname <defensoft at gmail.com> wrote:
> Hello!
>
> The attached file 'cameramovement.py' is very laggy. Could someone help me
> out by telling me what part of this is slowing it down so much? ?I've
> checked the whole file through, and I can't see why it's so slow. You'll
> have to place the pngs and bmps in the folder data/test, and the other pys
> in the same folder with cameramovement. Thanks!
>
> Thanks
> -Defenestrator.
>
>
> P.S. - I know that the load time is long. ?That is not the problem I have.
>

The game runs at a solid 62.5 fps on my computer (well, I assume
that's what the number in the top right means anyway). I experience
zero lag or choppy movement whatsoever. Sounds to me like you're
computer might simply be too slow to run it?

For the record, my system specs: 64bit Windows 7, i5-2500k @ 3.3 GHz,
8GB RAM, GeForce GTX 560 Ti. Python 2.7.2, pygame 1.9.2pre

Hugo

From hugo.yoshi at gmail.com  Tue Jan 10 19:05:33 2012
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Tue, 10 Jan 2012 19:05:33 +0100
Subject: [Tutor] Removing certain sequences from a string list elements
In-Reply-To: <CAMe-Gs-d96hEmo-29CmNJwUEP+yh4Tsu4mEZEW-tMPjNu+1i2A@mail.gmail.com>
References: <CAMe-Gs-d96hEmo-29CmNJwUEP+yh4Tsu4mEZEW-tMPjNu+1i2A@mail.gmail.com>
Message-ID: <CAJmBOf=vPO=vkSCK-JwYCA8M-jRgqdewWd2rFAaA+ucUc8y=Jw@mail.gmail.com>

On Sat, Jan 7, 2012 at 2:08 AM, Varsha Purohit <varsha.purohit at gmail.com> wrote:
> Hello,
>
> I have a simple python program where I am comparing two log files and I am
> storing the differences in a list. I am programming in python after a long
> time so may be I might have not written something very efficient. Please let
> me know what alternate solution I can apply for my program.
>
> I am reading each line in the file individually and storing them in a list.
> After that i am comparing the two lists and printing out the differences.
> But I wanted to know how can I iter through each string in the list and
> remove certain sequences like \n and ',' comma. I want to basically printout
> a column where it has each element of the list in each row. It?should?also
> avoid priting the time stamp since they will be different anyway. i want the
> program as simple as it looks right now.
>
> Input file contains something like this in each line. I have not included
> the complete log file.
>
> MegaMon> mfc
> MFC data:
> ? ? vendorId/deviceId=1000/005b, subVendorId/subDeviceId=1000/9285, OEM=1,
> SubOem=1, isRaidKeySecondary=0
> ? ? MFCF: disableSAS=0, maxDisks=0, enableRaid6=1, disableWideCache=0
> ? ? disableRaid5=0, enableSecurity=0, enableReducedFeatureSet=0
> ? ? enableCTIO=0 enableSnapshot=1 enableSSC=1 enableCacheOffload=0
> ? ? maxHANodes=2
>
>
> here is the program
>
> def readList1():
> ? ? f1 = open('mfc_node1.txt',"r")
> ? ? lines = f1.read().split(" ")
> ? ? q = []
> ? ? for line in lines:
> ? ? ? ? if not line in q:
> ? ? ? ? ? ? q.append(line)
> ? ? f1.close()
> ? ? return q
>
> def readList2():
> ? ? f = open('mfc_node2.txt',"r")
> ? ? lines = f.read().split(" ")
> ? ? p = []
> ? ? for line in lines:
> ? ? ? ? if not line in p:
> ? ? ? ? ? ? p.append(line)
> ? ? f.close()
> ? ? return p
>
>

These two functions should be one function that takes a filename as
argument. They are exactly the same. For removing commas and newlines,
you should google the str.strip() method.

From enalicho at gmail.com  Tue Jan 10 19:47:31 2012
From: enalicho at gmail.com (Noah Hall)
Date: Tue, 10 Jan 2012 18:47:31 +0000
Subject: [Tutor] x%2
In-Reply-To: <AD3F5192CD7C4FC6B8F8F731503A940F@workstation>
References: <08EE20443EDD47C4BA5C0E843927DA26@workstation>
	<CAOv69sZEWXcxJqdTA=hP606F-3wbRraeUZcE+K6A8486n9L+PA@mail.gmail.com>
	<AD3F5192CD7C4FC6B8F8F731503A940F@workstation>
Message-ID: <CAOv69sbYADAVBiRMgDfZ2NYB5+htaQZWSG8q=Cvh-NNtnf2KmQ@mail.gmail.com>

On Tue, Jan 10, 2012 at 6:24 PM, emin <oldcowboyrocky at gmail.com> wrote:
> answers = ["yes","no"]
> reaction = ["OK.I GOT IT.But why symbol of percent % not symbol of division
> / ?","PLEASE EXPLAIN MORE"]
>
> print "1st SORRY FOR BAD ENGLISH & DISTURBING:((i am beginner)"
> print "So you want to say it doesnt mean 2 percent of x and it means x
> divisible by 2?"
> print "Yes"
> print "or"
> print "No"
> answerChoise = raw_input("Type here: ")
>
> if answerChoise == "yes" or answerChoise == "Yes":
> ? print reaction[0]
>
> elif answerChoise == "no" or answerChoise == "No":
> ? print reaction[1]

Urm, yeah, while this is cute and all, it's not a great way of asking
a question.

I'm not totally sure what you mean, so I'm just going to say -

a / b is the division operator. It divides things. It returns a divided by b.
a % b is the remainder operator. It returns what's "left" after dividing a by b.

From joel.goldstick at gmail.com  Tue Jan 10 20:22:59 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 10 Jan 2012 14:22:59 -0500
Subject: [Tutor] x%2
In-Reply-To: <CAOv69sbYADAVBiRMgDfZ2NYB5+htaQZWSG8q=Cvh-NNtnf2KmQ@mail.gmail.com>
References: <08EE20443EDD47C4BA5C0E843927DA26@workstation>
	<CAOv69sZEWXcxJqdTA=hP606F-3wbRraeUZcE+K6A8486n9L+PA@mail.gmail.com>
	<AD3F5192CD7C4FC6B8F8F731503A940F@workstation>
	<CAOv69sbYADAVBiRMgDfZ2NYB5+htaQZWSG8q=Cvh-NNtnf2KmQ@mail.gmail.com>
Message-ID: <CAPM-O+wHxoZq1RtWWpTcVYfEJ6-iQCnGyroCiURYmfsVFH8onw@mail.gmail.com>

On Tue, Jan 10, 2012 at 1:47 PM, Noah Hall <enalicho at gmail.com> wrote:
> On Tue, Jan 10, 2012 at 6:24 PM, emin <oldcowboyrocky at gmail.com> wrote:
>> answers = ["yes","no"]
>> reaction = ["OK.I GOT IT.But why symbol of percent % not symbol of division
>> / ?","PLEASE EXPLAIN MORE"]
>>
>> print "1st SORRY FOR BAD ENGLISH & DISTURBING:((i am beginner)"
>> print "So you want to say it doesnt mean 2 percent of x and it means x
>> divisible by 2?"
>> print "Yes"
>> print "or"
>> print "No"
>> answerChoise = raw_input("Type here: ")
>>
>> if answerChoise == "yes" or answerChoise == "Yes":
>> ? print reaction[0]
>>
>> elif answerChoise == "no" or answerChoise == "No":
>> ? print reaction[1]
>
> Urm, yeah, while this is cute and all, it's not a great way of asking
> a question.
>
> I'm not totally sure what you mean, so I'm just going to say -
>
> a / b is the division operator. It divides things. It returns a divided by b.
> a % b is the remainder operator. It returns what's "left" after dividing a by b.
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



-- 

The / operator signifies division.  The % signifies modulo.  see this:
http://en.wikipedia.org/wiki/Modulo_operation

and see this: http://docs.python.org/reference/expressions.html#index-998
Joel Goldstick

From badouglas at gmail.com  Tue Jan 10 21:24:46 2012
From: badouglas at gmail.com (bruce)
Date: Tue, 10 Jan 2012 15:24:46 -0500
Subject: [Tutor] generating unique set of dicts from a list of dicts
Message-ID: <CAP16ngr5C6tdY=3AHCFb=J2id-qF=75DXAmUcek2Ffet9y0ivQ@mail.gmail.com>

trying to figure out how to generate a unique set of dicts from a
json/list of dicts.

initial list :::
[{"pStart1a": {"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI",
"instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH",
"pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"},
"pSearch1a":
{"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}},
 {"pStart1":""},
 {"pStart1a":{"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI",
 "instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH",
 "pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"},
 "pSearch1a":
 {"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}},
 {"pStart1":""}]



As an exmple, the following is the test list:

[{"pStart1a": {"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI",
"instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH",
"pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"},
"pSearch1a":
{"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}},
 {"pStart1":""},
 {"pStart1a":{"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI",
 "instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH",
 "pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"},
 "pSearch1a":
 {"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}},
 {"pStart1":""}]

Trying to get the following, list of unique dicts, so there aren't
duplicate dicts.
 Searched various sites/SO.. and still have a mental block.

[
  {"pStart1a":
  {"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI",
   "instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH",
   pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"},
  "pSearch1a":
  {"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}},
  {"pStart1":""}]

I was considering iterating through the initial list, copying each
dict into a new list, and doing a basic comparison, adding the next
dict if it's not in the new list.. is there another/better way?

posted this to StackOverflow as well.  >>>>
http://stackoverflow.com/questions/8808286/simplifying-a-json-list-to-the-unique-dict-items
 <<<

There was a potential soln that I couldn't understand.

	
-------------------------
The simplest approach -- using list(set(your_list_of_dicts)) won't
work because Python dictionaries are mutable and not hashable (that
is, they don't implement __hash__). This is because Python can't
guarantee that the hash of a dictionary won't change after you insert
it into a set or dict.

However, in your case, since you (don't seem to be) modifying the data
at all, you can compute your own hash, and use this along with a
dictionary to relatively easily find the unique JSON objects without
having to do a full recursive comparison of each dictionary to the
others.

First, we need a function to compute a hash of the dictionary. Rather
than trying to build our own hash function, let's use one of the
built-in ones from hashlib:

def dict_hash(d):
    out = hashlib.md5()
    for key, value in d.iteritems():
        out.update(unicode(key))
        out.update(unicode(value))
    return out.hexdigest()

(Note that this relies on unicode(...) for each of your values
returning something unique -- if you have custom classes in the
dictionaries whose __unicode__ returns something like "MyClass
instance", this will fail or will require modification. Also, in your
example, your dictionaries are flat, but I'll leave it as an exercise
to the reader how to expand this solution to work with dictionaries
that contain other dicts or lists.)

Since dict_hash returns a string, which is immutable, you can now use
a dictionary to find the unique elements:

uniques_map = {}
for d in list_of_dicts:
    uniques[dict_hash(d)] = d
unique_dicts = uniques_map.values()

>>>>*** not sure what the "uniqes" is, or what/how it should be defined....


thoughts/comments are welcome

thanks

From d at davea.name  Tue Jan 10 21:49:27 2012
From: d at davea.name (Dave Angel)
Date: Tue, 10 Jan 2012 15:49:27 -0500
Subject: [Tutor] generating unique set of dicts from a list of dicts
In-Reply-To: <CAP16ngr5C6tdY=3AHCFb=J2id-qF=75DXAmUcek2Ffet9y0ivQ@mail.gmail.com>
References: <CAP16ngr5C6tdY=3AHCFb=J2id-qF=75DXAmUcek2Ffet9y0ivQ@mail.gmail.com>
Message-ID: <4F0CA457.5040402@davea.name>

On 01/10/2012 03:24 PM, bruce wrote:
> <SNIP>
> Since dict_hash returns a string, which is immutable, you can now use
> a dictionary to find the unique elements:
>
> uniques_map = {}
> for d in list_of_dicts:
>      uniques[dict_hash(d)] = d
> unique_dicts = uniques_map.values()
>
>>>>> *** not sure what the "uniqes" is, or what/how it should be defined....
Don't know about the rest of the message, but I think there's a typo in 
the above fragment.  On the third line, it should be uniques_map, not 
uniques that you're adding an item to.

And unless you have a really long (and strong) hash, you still have to 
check for actually equal.  In otherwords, the above solution will throw 
out a dict that happens to have the same hash as one already in the 
uniques_map.

Do you trust the  "equals" method  for your dicts ?  If not, that's your 
first problem.  If you do, then you can simply do

unique_dicts = []
for d in list_of_dicts:
      if d not in unique_dicts:
            unique_dicts.append(d)

Do it, then decide if performance is inadequate.  Only then  should you 
worry about faster methods, especially if the faster method is broken.



-- 

DaveA


From bgailer at gmail.com  Tue Jan 10 21:53:37 2012
From: bgailer at gmail.com (bob gailer)
Date: Tue, 10 Jan 2012 15:53:37 -0500
Subject: [Tutor] x%2
In-Reply-To: <CAOv69sbYADAVBiRMgDfZ2NYB5+htaQZWSG8q=Cvh-NNtnf2KmQ@mail.gmail.com>
References: <08EE20443EDD47C4BA5C0E843927DA26@workstation>
	<CAOv69sZEWXcxJqdTA=hP606F-3wbRraeUZcE+K6A8486n9L+PA@mail.gmail.com>
	<AD3F5192CD7C4FC6B8F8F731503A940F@workstation>
	<CAOv69sbYADAVBiRMgDfZ2NYB5+htaQZWSG8q=Cvh-NNtnf2KmQ@mail.gmail.com>
Message-ID: <4F0CA551.3030503@gmail.com>

On 1/10/2012 1:47 PM, Noah Hall wrote:
> a % b is the remainder operator. It returns what's "left" after 
> dividing a by b. 
Not to beat a dead horse- but % is the modulo operator.

It returns the residue class of the 2 operands. When a is positive this 
is the same as remainder, but not so for negative a.

 >>> 5%3
2
 >>> -5%3
1
 >>>

FWIW the Python documentation (at least as of 2.7.2 has this wrong!)


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


From kellyadrian at hotmail.com  Tue Jan 10 20:31:35 2012
From: kellyadrian at hotmail.com (Adrian)
Date: Tue, 10 Jan 2012 19:31:35 +0000
Subject: [Tutor] Defining a File path
Message-ID: <BLU0-SMTP33032C3D584E464B3CE19DBA9990@phx.gbl>

Hi guys,
I know that if i dont include any path information, python looks in the current directory for the file. My question is how do i specify a file path to open a file saved on my desktop for example. 

Thanks all

Adrian

Sent from my iPad

From __peter__ at web.de  Tue Jan 10 22:53:15 2012
From: __peter__ at web.de (Peter Otten)
Date: Tue, 10 Jan 2012 22:53:15 +0100
Subject: [Tutor] generating unique set of dicts from a list of dicts
References: <CAP16ngr5C6tdY=3AHCFb=J2id-qF=75DXAmUcek2Ffet9y0ivQ@mail.gmail.com>
	<4F0CA457.5040402@davea.name>
Message-ID: <jeic00$hsj$1@dough.gmane.org>

[NN]
>> uniques_map = {}
>> for d in list_of_dicts:
>>      uniques[dict_hash(d)] = d
>> unique_dicts = uniques_map.values()

[Dave Angel] 
> unique_dicts = []
> for d in list_of_dicts:
>       if d not in unique_dicts:
>             unique_dicts.append(d)
> 
> Do it, then decide if performance is inadequate.  Only then  should you
> worry about faster methods, especially if the faster method is broken.

Another variant:

# keys and values in the dictionaries must be hashable
list_of_dicts = ...

unique_dicts_map = {}
for d in list_of_dicts:
    key = frozenset(d.items())
    unique_dicts_map[key] = d 

unique_dicts = unique_dicts_map.values()

I'm using a frozenset because it is hashable. It should be easy to see that 
two dicts are equal if and only if they comprise a set of equal key-value 
pairs.




From emile at fenx.com  Tue Jan 10 22:56:59 2012
From: emile at fenx.com (Emile van Sebille)
Date: Tue, 10 Jan 2012 13:56:59 -0800
Subject: [Tutor] Defining a File path
In-Reply-To: <BLU0-SMTP33032C3D584E464B3CE19DBA9990@phx.gbl>
References: <BLU0-SMTP33032C3D584E464B3CE19DBA9990@phx.gbl>
Message-ID: <jeic28$iav$1@dough.gmane.org>

On 1/10/2012 11:31 AM Adrian said...
> Hi guys,
> I know that if i dont include any path information, python looks
> in the current directory for the file. My question is how do i
 > specify a file path to open a file saved on my desktop for example.

There's lots of ways that depend on your platform and specific needs.

Google python path search for some ideas, and ask with more specifics.

Emile



From hugo.yoshi at gmail.com  Tue Jan 10 22:53:36 2012
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Tue, 10 Jan 2012 22:53:36 +0100
Subject: [Tutor] Defining a File path
In-Reply-To: <BLU0-SMTP33032C3D584E464B3CE19DBA9990@phx.gbl>
References: <BLU0-SMTP33032C3D584E464B3CE19DBA9990@phx.gbl>
Message-ID: <CAJmBOfk+THE5SZuUajgROt=USXqsTXZ0SKdyZOpK1_Z-3x22_w@mail.gmail.com>

On Tue, Jan 10, 2012 at 8:31 PM, Adrian <kellyadrian at hotmail.com> wrote:
> Hi guys,
> I know that if i dont include any path information, python looks in the current directory for the file. My question is how do i specify a file path to open a file saved on my desktop for example.
>
> Thanks all
>
> Adrian
>

Just write the path like you would anywhere else, there is nothing
special about how python handles this.

# this is where my desktop is located on my windows 7 machine, but it
differs per operating system of course
f = open("C:\Users\hugo\Desktop\file.txt", 'r')

# you can also use relative paths, like "two directories up from the
current and then into the media directory"
# forward slashes here, that's what they use on essentially everything
that isn't windows
f = open("../../media/file.txt", 'r')

if you want to be cross-platform, you should take a look at the os.path module.

HTH,
Hugo

From steve at pearwood.info  Tue Jan 10 22:58:35 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 11 Jan 2012 08:58:35 +1100
Subject: [Tutor] x%2
In-Reply-To: <4F0CA551.3030503@gmail.com>
References: <08EE20443EDD47C4BA5C0E843927DA26@workstation>	<CAOv69sZEWXcxJqdTA=hP606F-3wbRraeUZcE+K6A8486n9L+PA@mail.gmail.com>	<AD3F5192CD7C4FC6B8F8F731503A940F@workstation>	<CAOv69sbYADAVBiRMgDfZ2NYB5+htaQZWSG8q=Cvh-NNtnf2KmQ@mail.gmail.com>
	<4F0CA551.3030503@gmail.com>
Message-ID: <4F0CB48B.8090806@pearwood.info>

bob gailer wrote:
> On 1/10/2012 1:47 PM, Noah Hall wrote:
>> a % b is the remainder operator. It returns what's "left" after 
>> dividing a by b. 
> Not to beat a dead horse- but % is the modulo operator.

That depends on how you define "remainder" and "modulo". There is no 
definition agreed on by all people, and so we get into terminology disputes.

To a mathematician, "modulo operator" is meaningless. Modulo is a modifier to 
a statement, not an operator, and is written "mod" as in:

1 = 5*3 mod 7


> It returns the residue class of the 2 operands. When a is positive this 
> is the same as remainder, but not so for negative a.

"Remainder" is ambiguous for negative values. -7/5 could be given as -1 with 
-2 remainder, or as -2 with 3 remainder. One might define a remainder 
operation as returning a result:

- which is always positive
- with the sign of the divisor
- with the sign of the dividend
- which is closest to zero
- which is furthest away from zero

The last two require further variations, depending on how you resolve ties.

One might also define i%0 to be i, or as undefined. So by my count, there are 
at least 18 consistent ways to define a remainder/modulo operator.

A very few languages define two operators, or functions, e.g. Ada defines a 
rem operator which returns the remainder with the sign of the dividend and a 
mod operator which returns the remainder with the sign of the operator.


-- 
Steven

From d at davea.name  Tue Jan 10 23:24:06 2012
From: d at davea.name (Dave Angel)
Date: Tue, 10 Jan 2012 17:24:06 -0500
Subject: [Tutor] Defining a File path
In-Reply-To: <CAJmBOfk+THE5SZuUajgROt=USXqsTXZ0SKdyZOpK1_Z-3x22_w@mail.gmail.com>
References: <BLU0-SMTP33032C3D584E464B3CE19DBA9990@phx.gbl>
	<CAJmBOfk+THE5SZuUajgROt=USXqsTXZ0SKdyZOpK1_Z-3x22_w@mail.gmail.com>
Message-ID: <4F0CBA86.1040505@davea.name>

On 01/10/2012 04:53 PM, Hugo Arts wrote:
> On Tue, Jan 10, 2012 at 8:31 PM, Adrian<kellyadrian at hotmail.com>  wrote:
>> Hi guys,
>> I know that if i dont include any path information, python looks in the current directory for the file. My question is how do i specify a file path to open a file saved on my desktop for example.
>>
>> Thanks all
>>
>> Adrian
>>
> Just write the path like you would anywhere else, there is nothing
> special about how python handles this.
>
> # this is where my desktop is located on my windows 7 machine, but it
> differs per operating system of course
> f = open("C:\Users\hugo\Desktop\file.txt", 'r')
>
You'd want to do one of three things there:

1) use forward slashes
                    "C:/Users/hugo/Desktop/file.txt"
       which Windows will use happily for nearly every purpose.

2) use raw strings
                   r"C:\Users\hugo\Desktop\file.txt"

3) or escape the backslashes:
                     "C:\\Users\\hugo\\Desktop\\file.txt"

> # you can also use relative paths, like "two directories up from the
> current and then into the media directory"
> # forward slashes here, that's what they use on essentially everything
> that isn't windows
> f = open("../../media/file.txt", 'r')
>
> if you want to be cross-platform, you should take a look at the os.path module.
>
> HTH,
> Hugo
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 

DaveA


From c.johnsonbl at gmail.com  Wed Jan 11 08:14:47 2012
From: c.johnsonbl at gmail.com (Chris Johnson)
Date: Wed, 11 Jan 2012 01:14:47 -0600
Subject: [Tutor] Extremely simple question
Message-ID: <CAEf1y-oUFNMqyF9CVbQtnP9Y7fnQKKZsUy_KagvuLAP3HKjgVA@mail.gmail.com>

Hi there,

I am *new* (I cannot put enough emphasis on that!) to Python programming,
and to programming in general. I am trying to write out a statement that
will protect a file on my computer from being run unless I enter the right
specifications;

your_weight = int(raw_input("Please enter your weight: "))
> if your_weight < 0:
> print 'You're not Chris!'
> elif your_weight == 170:
> print 'You might be Chris! But...'
> your_height = int(raw_input("Please enter your height: "))
> if your_height < 180:
> print 'You're not Chris!
> elif your_height == 180:
> print 'You're Chris!'
> your_name = int(raw_input("What is your name? "))
> elif your_height > 180:
> print 'You're not Chris!"
> elif x > 170:
> print 'You're not Chris!'


When I open it, the program says I have a syntax error. Praytell, where did
I go wrong?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120111/51e4cd04/attachment-0001.html>

From enalicho at gmail.com  Wed Jan 11 08:24:24 2012
From: enalicho at gmail.com (Noah Hall)
Date: Wed, 11 Jan 2012 07:24:24 +0000
Subject: [Tutor] Extremely simple question
In-Reply-To: <CAEf1y-oUFNMqyF9CVbQtnP9Y7fnQKKZsUy_KagvuLAP3HKjgVA@mail.gmail.com>
References: <CAEf1y-oUFNMqyF9CVbQtnP9Y7fnQKKZsUy_KagvuLAP3HKjgVA@mail.gmail.com>
Message-ID: <CAOv69sY9zGzTm7y-xZZx9rDDt5giHZUBz3XNEg3NPpryWCEksQ@mail.gmail.com>

On Wed, Jan 11, 2012 at 7:14 AM, Chris Johnson <c.johnsonbl at gmail.com> wrote:
> Hi there,
>
> I am *new* (I cannot put enough emphasis on that!) to Python programming,
> and to programming in general. I am trying to write out a statement that
> will protect a file on my computer from being run unless I enter the right
> specifications;
>
>> your_weight = int(raw_input("Please enter your weight: "))
>> if your_weight < 0:
>> print 'You're not Chris!'
>> elif your_weight == 170:
>> print 'You might be Chris! But...'
>> your_height = int(raw_input("Please enter your height: "))
>> if your_height < 180:
>> print 'You're not Chris!
>> elif your_height == 180:
>> print 'You're Chris!'
>> your_name = int(raw_input("What is your name? "))
>> elif your_height > 180:
>> print 'You're not Chris!"
>> elif x > 170:
>> print 'You're not Chris!'
>
>
> When I open it, the program says I have a syntax error. Praytell, where did
> I go wrong?

When you have a problem like this, you should copy and paste the
*whole* traceback here. Anyway, just from quickly looking, I think
your error lines in the the line

elif x > 170:

I'm sure you can work out why.

From stm.at.oc at googlemail.com  Wed Jan 11 11:08:55 2012
From: stm.at.oc at googlemail.com (stm atoc)
Date: Wed, 11 Jan 2012 11:08:55 +0100
Subject: [Tutor] changing coordinate
Message-ID: <CAHNhTs4exu11D-Lv5HDuuUyEf_9NF8io_W014H0MtEgHeOWCKA@mail.gmail.com>

Hi:

I am trying to define a new coordinate for My plot.

I have a plot x axis is Concentration, Y axis, depth or Z.

Z= -1000 um.
and I would like to see the the trend and plot of concentration up to
-300 um and see how the plot changed according to the depth. So, my
main question is about how to change the coordinate based on 0 to
-300.

This is the relevant description:

# coding: utf-8
from pylab import *
import numpy
import matplotlib.pyplot as pyplot
import matplotlib.mlab as mlab

#t=3600
N = 100
dz = 1.0
h_s=-300


with open("ourtest_out.list", "r") as f:
   z = numpy.array([float(v) for v in f.readline().split()[1:]])

z == z + h_s
a = numpy.loadtxt("ourtest_out.list", skiprows=3)
t=a[:,0]

nu = a[0:,1:N+1]
Conc = a[0:, N+1:]

lw = 2.0 #linewidth
dpi = 96
figure(figsize=(12,6),dpi=dpi)

pyplot.plot(Conc[1], z,'r-')
pyplot.xlabel('$Conc, mmol C m^3$')
pyplot.ylabel('$Hsml, micrometer$')
pyplot.grid(True)

legend()
savefig('Conc.png')
show()


lw = 2.0 #linewidth
dpi = 96
figure(figsize=(12,6),dpi=dpi)
semilogx(Conc[1], z,'r-')
pyplot.xlabel('$Conc, mmol C m^3$')
pyplot.ylabel('$Hsml, micrometer$')
pyplot.grid(True)

legend()
savefig('semiConc.png')
show()


lw = 2.0 #linewidth
dpi = 96
figure(figsize=(12,6),dpi=dpi)

semilogx(nu[1], z,'r-')
pyplot.xlabel('$nu, m^2/s^{-1}$')
pyplot.ylabel('$Hsml, micrometer$')
pyplot.grid(True)

legend()
savefig('nu.png')
show()
--------------
I do appreciate any help and advice.

Thanks,Sue

From steve at pearwood.info  Wed Jan 11 11:24:27 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 11 Jan 2012 21:24:27 +1100
Subject: [Tutor] Extremely simple question
In-Reply-To: <CAOv69sY9zGzTm7y-xZZx9rDDt5giHZUBz3XNEg3NPpryWCEksQ@mail.gmail.com>
References: <CAEf1y-oUFNMqyF9CVbQtnP9Y7fnQKKZsUy_KagvuLAP3HKjgVA@mail.gmail.com>
	<CAOv69sY9zGzTm7y-xZZx9rDDt5giHZUBz3XNEg3NPpryWCEksQ@mail.gmail.com>
Message-ID: <4F0D635B.2060004@pearwood.info>

Noah Hall wrote:
> On Wed, Jan 11, 2012 at 7:14 AM, Chris Johnson <c.johnsonbl at gmail.com> wrote:
>> Hi there,
>>
>> I am *new* (I cannot put enough emphasis on that!) to Python programming,
>> and to programming in general. I am trying to write out a statement that
>> will protect a file on my computer from being run unless I enter the right
>> specifications;
>>
>>> your_weight = int(raw_input("Please enter your weight: "))
>>> if your_weight < 0:
>>> print 'You're not Chris!'
>>> elif your_weight == 170:
>>> print 'You might be Chris! But...'
>>> your_height = int(raw_input("Please enter your height: "))
>>> if your_height < 180:
>>> print 'You're not Chris!
>>> elif your_height == 180:
>>> print 'You're Chris!'
>>> your_name = int(raw_input("What is your name? "))
>>> elif your_height > 180:
>>> print 'You're not Chris!"
>>> elif x > 170:
>>> print 'You're not Chris!'
>>
>> When I open it, the program says I have a syntax error. Praytell, where did
>> I go wrong?
> 
> When you have a problem like this, you should copy and paste the
> *whole* traceback here. Anyway, just from quickly looking, I think
> your error lines in the the line
> 
> elif x > 170:
> 
> I'm sure you can work out why.

Well, I can't. Chris reported that he gets a SYNTAX error, and for the life of 
me I can't work out what SyntaxError you think he'll be getting from that line.

Based on Chris' post, he has a whole lot of code starting with ">", which of 
course will give a SyntaxError. He also hasn't indented his if/elif blocks.

But of course his mail client might be mangling his code. Without being able 
to see the code, and the actual error message in full, we're all just 
guessing. And frankly, my crystal ball is out of order.



-- 
Steven

From enalicho at gmail.com  Wed Jan 11 11:29:56 2012
From: enalicho at gmail.com (Noah Hall)
Date: Wed, 11 Jan 2012 10:29:56 +0000
Subject: [Tutor] Extremely simple question
In-Reply-To: <4F0D635B.2060004@pearwood.info>
References: <CAEf1y-oUFNMqyF9CVbQtnP9Y7fnQKKZsUy_KagvuLAP3HKjgVA@mail.gmail.com>
	<CAOv69sY9zGzTm7y-xZZx9rDDt5giHZUBz3XNEg3NPpryWCEksQ@mail.gmail.com>
	<4F0D635B.2060004@pearwood.info>
Message-ID: <CAOv69saboAmaGMhXJ+tfEN6h0XGEtOvivpfO489UE9eW1uLCJw@mail.gmail.com>

On Wed, Jan 11, 2012 at 10:24 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> Noah Hall wrote:
>>
>> On Wed, Jan 11, 2012 at 7:14 AM, Chris Johnson <c.johnsonbl at gmail.com>
>> wrote:
>>>
>>> Hi there,
>>>
>>> I am *new* (I cannot put enough emphasis on that!) to Python programming,
>>> and to programming in general. I am trying to write out a statement that
>>> will protect a file on my computer from being run unless I enter the
>>> right
>>> specifications;
>>>
>>>> your_weight = int(raw_input("Please enter your weight: "))
>>>> if your_weight < 0:
>>>> print 'You're not Chris!'
>>>> elif your_weight == 170:
>>>> print 'You might be Chris! But...'
>>>> your_height = int(raw_input("Please enter your height: "))
>>>> if your_height < 180:
>>>> print 'You're not Chris!
>>>> elif your_height == 180:
>>>> print 'You're Chris!'
>>>> your_name = int(raw_input("What is your name? "))
>>>> elif your_height > 180:
>>>> print 'You're not Chris!"
>>>> elif x > 170:
>>>> print 'You're not Chris!'
>>>
>>>
>>> When I open it, the program says I have a syntax error. Praytell, where
>>> did
>>> I go wrong?
>>
>>
>> When you have a problem like this, you should copy and paste the
>> *whole* traceback here. Anyway, just from quickly looking, I think
>> your error lines in the the line
>>
>> elif x > 170:
>>
>> I'm sure you can work out why.
>
>
> Well, I can't. Chris reported that he gets a SYNTAX error, and for the life
> of me I can't work out what SyntaxError you think he'll be getting from that
> line.
>
> Based on Chris' post, he has a whole lot of code starting with ">", which of
> course will give a SyntaxError. He also hasn't indented his if/elif blocks.
>
> But of course his mail client might be mangling his code. Without being able
> to see the code, and the actual error message in full, we're all just
> guessing. And frankly, my crystal ball is out of order.

I had assumed that to him, a Syntax Error == any error, so guess it
was probably a name error as x isn't defined.

(Also, for me his post was indented correctly - probably down to my
client, though)

From ajarncolin at gmail.com  Wed Jan 11 12:04:46 2012
From: ajarncolin at gmail.com (col speed)
Date: Wed, 11 Jan 2012 18:04:46 +0700
Subject: [Tutor] Extremely simple question
In-Reply-To: <CAOv69saboAmaGMhXJ+tfEN6h0XGEtOvivpfO489UE9eW1uLCJw@mail.gmail.com>
References: <CAEf1y-oUFNMqyF9CVbQtnP9Y7fnQKKZsUy_KagvuLAP3HKjgVA@mail.gmail.com>
	<CAOv69sY9zGzTm7y-xZZx9rDDt5giHZUBz3XNEg3NPpryWCEksQ@mail.gmail.com>
	<4F0D635B.2060004@pearwood.info>
	<CAOv69saboAmaGMhXJ+tfEN6h0XGEtOvivpfO489UE9eW1uLCJw@mail.gmail.com>
Message-ID: <CAKLa6jSSti+1voXWdSMGwCmJXBS2PdFuKKzdFwoaT3NaOYHZWg@mail.gmail.com>

>>>>
>>>>> your_weight = int(raw_input("Please enter your weight: "))
>>>>> if your_weight < 0:
>>>>> print 'You're not Chris!'
>>>>> elif your_weight == 170:
>>>>> print 'You might be Chris! But...'
>>>>> your_height = int(raw_input("Please enter your height: "))
>>>>> if your_height < 180:
>>>>> print 'You're not Chris!
>>>>> elif your_height == 180:
>>>>> print 'You're Chris!'
>>>>> your_name = int(raw_input("What is your name? "))
>>>>> elif your_height > 180:
>>>>> print 'You're not Chris!"
>>>>> elif x > 170:
>>>>> print 'You're not Chris!'
>>>>
>>>>
>>>> When I open it, the program says I have a syntax error. Praytell, where
>>>> did
>>>> I go wrong?n
I'm a newbie, but I get "NameError" because 'x' is not defined.
Also "your_name = int(raw_input("What is your name? "))" will give this :
ValueError: invalid literal for int() with base 10: 'name'.
As you can't change a string to be an int.
I can't find a syntax error, but next time, please paste the whole
traceback as this helps people with less time than me to sort out
problems.

Good luck with Python
Col

From evert.rol at gmail.com  Wed Jan 11 12:32:52 2012
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 11 Jan 2012 12:32:52 +0100
Subject: [Tutor] changing coordinate
In-Reply-To: <CAHNhTs4exu11D-Lv5HDuuUyEf_9NF8io_W014H0MtEgHeOWCKA@mail.gmail.com>
References: <CAHNhTs4exu11D-Lv5HDuuUyEf_9NF8io_W014H0MtEgHeOWCKA@mail.gmail.com>
Message-ID: <21CC4267-1598-4ED3-921D-77545DF93982@gmail.com>

  Hi Sue,

> I am trying to define a new coordinate for My plot.
> 
> I have a plot x axis is Concentration, Y axis, depth or Z.
> 
> Z= -1000 um.
> and I would like to see the the trend and plot of concentration up to
> -300 um and see how the plot changed according to the depth. So, my
> main question is about how to change the coordinate based on 0 to
> -300.

I'm not exactly sure what you want, but it sounds you just want to change the yaxis scaling. 
If that's the case, use pylot.axis or pyplot.ylim (see the matplotlib documentation if necessary).

If you're just trying to subtract 300 from your z values, I think this part of your code:

> z == z + h_s

has the problem: it's a comparison, not an assignment, because of the double '==' (presumably a simple but unfortunate typo).

If it's something else, you might need to clarify your description or give an example.

Cheers,

  Evert


> 
> This is the relevant description:
> 
> # coding: utf-8
> from pylab import *
> import numpy
> import matplotlib.pyplot as pyplot
> import matplotlib.mlab as mlab
> 
> #t=3600
> N = 100
> dz = 1.0
> h_s=-300
> 
> 
> with open("ourtest_out.list", "r") as f:
>   z = numpy.array([float(v) for v in f.readline().split()[1:]])
> 
> z == z + h_s
> a = numpy.loadtxt("ourtest_out.list", skiprows=3)
> t=a[:,0]
> 
> nu = a[0:,1:N+1]
> Conc = a[0:, N+1:]
> 
> lw = 2.0 #linewidth
> dpi = 96
> figure(figsize=(12,6),dpi=dpi)
> 
> pyplot.plot(Conc[1], z,'r-')
> pyplot.xlabel('$Conc, mmol C m^3$')
> pyplot.ylabel('$Hsml, micrometer$')
> pyplot.grid(True)
> 
> legend()
> savefig('Conc.png')
> show()
> 
> 
> lw = 2.0 #linewidth
> dpi = 96
> figure(figsize=(12,6),dpi=dpi)
> semilogx(Conc[1], z,'r-')
> pyplot.xlabel('$Conc, mmol C m^3$')
> pyplot.ylabel('$Hsml, micrometer$')
> pyplot.grid(True)
> 
> legend()
> savefig('semiConc.png')
> show()
> 
> 
> lw = 2.0 #linewidth
> dpi = 96
> figure(figsize=(12,6),dpi=dpi)
> 
> semilogx(nu[1], z,'r-')
> pyplot.xlabel('$nu, m^2/s^{-1}$')
> pyplot.ylabel('$Hsml, micrometer$')
> pyplot.grid(True)
> 
> legend()
> savefig('nu.png')
> show()
> --------------
> I do appreciate any help and advice.
> 
> Thanks,Sue
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From msg.ufo at gmail.com  Wed Jan 11 12:58:38 2012
From: msg.ufo at gmail.com (Mike G)
Date: Wed, 11 Jan 2012 03:58:38 -0800
Subject: [Tutor]  Extremely simple question
Message-ID: <CAHD43mpkSyLtVrm2WJUu9cBp=K5id6dRaNbAb2g3q2FQLwR-Kg@mail.gmail.com>

Hi Chris

I'm new to programming and Python myself so I would listen to the
previous guys first, and I'll repeat a bit of what has already been
mentioned...

Make sure you define 'x'. Is name really an 'int', or is it possibly a 'str'?

Fix any indentation issues.

Is there anything you can do with quotes - single or double:
print "You're not Chris!" or print 'You\'re not Chris!'

You should be able to make your code work as is but it would also look
nice in a function, passing the user 'raw_input' to a function -

def chris(name, height, weight):

From marco.vincenzo at gmail.com  Wed Jan 11 13:34:53 2012
From: marco.vincenzo at gmail.com (Marco Casazza)
Date: Wed, 11 Jan 2012 07:34:53 -0500
Subject: [Tutor] Is there a better way?
Message-ID: <4F0D81ED.6070103@gmail.com>

Hello,

I've been slowly teaching myself python, using it for small projects 
when it seems appropriate. In this case, I was handed a list of email 
addresses for a mailing but some of them had been truncated. There are 
only 21 possible email "suffixes" so I planned to just identify which it 
should be and then replace it. However, when I started writing the code 
I realized that I'd be doing a lot of "repeating". Is there a better way 
to "fix" the suffixes without doing each individually? Here's my working 
code (for 4 colleges):

import re
with file('c:\python27\mvc\mailing_list.txt', 'r') as infile:
     outlist = []
     for line in infile.read().split('\n'):
         if line.rstrip().lower().endswith('edu'):
             newline = line + '\n'
             outlist.append(newline.lower())
         elif re.search("@bar", line):
             newline = re.sub("@bar.*", "@baruch.cuny.edu", line)+'\n'
             outlist.append(newline.lower())
         elif re.search("@bcc", line):
             newline = re.sub("@bcc.*", "@bcc.cuny.edu", line)+'\n'
             outlist.append(newline.lower())
         elif re.search("@bmc", line):
             newline = re.sub("@bmc.*", "@bmcc.cuny.edu", line)+'\n'
             outlist.append(newline.lower())
         elif re.search("@leh", line):
             newline = re.sub("@leh.*", "@lehman.cuny.edu", line)+'\n'
             outlist.append(newline.lower())

with file('c:\python27\mvc\output.txt','w') as outfile:
     outfile.writelines(outlist)

Thanks,
Marco

From joel.goldstick at gmail.com  Wed Jan 11 13:57:26 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Wed, 11 Jan 2012 07:57:26 -0500
Subject: [Tutor] Is there a better way?
In-Reply-To: <4F0D81ED.6070103@gmail.com>
References: <4F0D81ED.6070103@gmail.com>
Message-ID: <CAPM-O+y2kAxj8tyKCYEhponYAGHbet-ObfLbJq+NNyzd4htVxg@mail.gmail.com>

On Wed, Jan 11, 2012 at 7:34 AM, Marco Casazza <marco.vincenzo at gmail.com> wrote:
> Hello,
>
> I've been slowly teaching myself python, using it for small projects when it
> seems appropriate. In this case, I was handed a list of email addresses for
> a mailing but some of them had been truncated. There are only 21 possible
> email "suffixes" so I planned to just identify which it should be and then
> replace it. However, when I started writing the code I realized that I'd be
> doing a lot of "repeating". Is there a better way to "fix" the suffixes
> without doing each individually? Here's my working code (for 4 colleges):
>
> import re
> with file('c:\python27\mvc\mailing_list.txt', 'r') as infile:
> ? ?outlist = []
> ? ?for line in infile.read().split('\n'):
> ? ? ? ?if line.rstrip().lower().endswith('edu'):
> ? ? ? ? ? ?newline = line + '\n'
> ? ? ? ? ? ?outlist.append(newline.lower())
> ? ? ? ?elif re.search("@bar", line):
> ? ? ? ? ? ?newline = re.sub("@bar.*", "@baruch.cuny.edu", line)+'\n'
> ? ? ? ? ? ?outlist.append(newline.lower())
> ? ? ? ?elif re.search("@bcc", line):
> ? ? ? ? ? ?newline = re.sub("@bcc.*", "@bcc.cuny.edu", line)+'\n'
> ? ? ? ? ? ?outlist.append(newline.lower())
> ? ? ? ?elif re.search("@bmc", line):
> ? ? ? ? ? ?newline = re.sub("@bmc.*", "@bmcc.cuny.edu", line)+'\n'
> ? ? ? ? ? ?outlist.append(newline.lower())
> ? ? ? ?elif re.search("@leh", line):
> ? ? ? ? ? ?newline = re.sub("@leh.*", "@lehman.cuny.edu", line)+'\n'
> ? ? ? ? ? ?outlist.append(newline.lower())
>
> with file('c:\python27\mvc\output.txt','w') as outfile:
> ? ?outfile.writelines(outlist)
>
> Thanks,
> Marco
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

First, look here about reading files:
http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects

I like this better:
    f = open('filename', 'r')
    for line in f:
        print line     # this will give you one line at a time without
the trailing newline

Second, make a dictionary of with the key being what comes after the @
in your truncated file.  The value will be the complete text you want:
 d = {"bcc" : "bcc.cuny.edu", etc. }

Third, use line.split('@') to split the line into what comes before
and after the @ sign.  It will return a list
    address_parts = line.split('@')

address_parts[0] is what you want to keep as is. I'm guessing that the
3 characters after the @ will be enough to identify what the full
address should look like, so
if address_parts[1][0:3] in d:
  result = '@'.join([address_parts[0], d[address_parts[1][0:3]])

write the result to your out file.

Its early in the morning for me, and this is untested, but it might
give you some ideas.

-- 
Joel Goldstick

From maxskywalker1 at gmail.com  Wed Jan 11 14:11:32 2012
From: maxskywalker1 at gmail.com (Max S.)
Date: Wed, 11 Jan 2012 08:11:32 -0500
Subject: [Tutor] Extremely simple question
In-Reply-To: <CAKLa6jSSti+1voXWdSMGwCmJXBS2PdFuKKzdFwoaT3NaOYHZWg@mail.gmail.com>
References: <CAEf1y-oUFNMqyF9CVbQtnP9Y7fnQKKZsUy_KagvuLAP3HKjgVA@mail.gmail.com>
	<CAOv69sY9zGzTm7y-xZZx9rDDt5giHZUBz3XNEg3NPpryWCEksQ@mail.gmail.com>
	<4F0D635B.2060004@pearwood.info>
	<CAOv69saboAmaGMhXJ+tfEN6h0XGEtOvivpfO489UE9eW1uLCJw@mail.gmail.com>
	<CAKLa6jSSti+1voXWdSMGwCmJXBS2PdFuKKzdFwoaT3NaOYHZWg@mail.gmail.com>
Message-ID: <CALXKb5Ptbcedb72YaQT1LToksRCYknEUUkrrBTcPmWwsbmmaVg@mail.gmail.com>

I believe that line 3 raises an error.  The because you contained the text
in single quotes, and then used the same character in 'you're not chris',
Python believes that you are trying to type "you" re not chris".  You can
change the single quotes surrounding your string to double quotes ("you're
not chris"), triple-single quotes ('''you're not chris'''), or
triple-double quotes ("""you're not chris"""), or you can tell Python that
you want to include the apostrophe in your string by preceding it with a \
('you\'re not chris').  The latter works on the same idea as \n and \t.

On Wed, Jan 11, 2012 at 6:04 AM, col speed <ajarncolin at gmail.com> wrote:

> >>>>
> >>>>> your_weight = int(raw_input("Please enter your weight: "))
> >>>>> if your_weight < 0:
> >>>>> print 'You're not Chris!'
> >>>>> elif your_weight == 170:
> >>>>> print 'You might be Chris! But...'
> >>>>> your_height = int(raw_input("Please enter your height: "))
> >>>>> if your_height < 180:
> >>>>> print 'You're not Chris!
> >>>>> elif your_height == 180:
> >>>>> print 'You're Chris!'
> >>>>> your_name = int(raw_input("What is your name? "))
> >>>>> elif your_height > 180:
> >>>>> print 'You're not Chris!"
> >>>>> elif x > 170:
> >>>>> print 'You're not Chris!'
> >>>>
> >>>>
> >>>> When I open it, the program says I have a syntax error. Praytell,
> where
> >>>> did
> >>>> I go wrong?n
> I'm a newbie, but I get "NameError" because 'x' is not defined.
> Also "your_name = int(raw_input("What is your name? "))" will give this :
> ValueError: invalid literal for int() with base 10: 'name'.
> As you can't change a string to be an int.
> I can't find a syntax error, but next time, please paste the whole
> traceback as this helps people with less time than me to sort out
> problems.
>
> Good luck with Python
> Col
> _______________________________________________
> 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/20120111/13756d57/attachment-0001.html>

From hugo.yoshi at gmail.com  Wed Jan 11 14:14:06 2012
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Wed, 11 Jan 2012 14:14:06 +0100
Subject: [Tutor] Defining a File path
In-Reply-To: <4F0CBA86.1040505@davea.name>
References: <BLU0-SMTP33032C3D584E464B3CE19DBA9990@phx.gbl>
	<CAJmBOfk+THE5SZuUajgROt=USXqsTXZ0SKdyZOpK1_Z-3x22_w@mail.gmail.com>
	<4F0CBA86.1040505@davea.name>
Message-ID: <CAJmBOfm4=MxeMbxuR7Pzh7zO5n7PmdTJVOYxTtunD06ywm5Kxw@mail.gmail.com>

On Tue, Jan 10, 2012 at 11:24 PM, Dave Angel <d at davea.name> wrote:
> On 01/10/2012 04:53 PM, Hugo Arts wrote:
>>
>> On Tue, Jan 10, 2012 at 8:31 PM, Adrian<kellyadrian at hotmail.com> ?wrote:
>>>
>>> Hi guys,
>>> I know that if i dont include any path information, python looks in the
>>> current directory for the file. My question is how do i specify a file path
>>> to open a file saved on my desktop for example.
>>>
>>> Thanks all
>>>
>>> Adrian
>>>
>> Just write the path like you would anywhere else, there is nothing
>> special about how python handles this.
>>
>> # this is where my desktop is located on my windows 7 machine, but it
>> differs per operating system of course
>> f = open("C:\Users\hugo\Desktop\file.txt", 'r')
>>
> You'd want to do one of three things there:
>
> 1) use forward slashes
> ? ? ? ? ? ? ? ? ? "C:/Users/hugo/Desktop/file.txt"
> ? ? ?which Windows will use happily for nearly every purpose.
>
> 2) use raw strings
>
> ? ? ? ? ? ? ? ? ?r"C:\Users\hugo\Desktop\file.txt"
>
> 3) or escape the backslashes:
>
> ? ? ? ? ? ? ? ? ? ?"C:\\Users\\hugo\\Desktop\\file.txt"
>

whoops. think before you type. Thanks for the correction

From ajarncolin at gmail.com  Wed Jan 11 14:17:07 2012
From: ajarncolin at gmail.com (col speed)
Date: Wed, 11 Jan 2012 20:17:07 +0700
Subject: [Tutor] Extremely simple question
In-Reply-To: <CALXKb5Ptbcedb72YaQT1LToksRCYknEUUkrrBTcPmWwsbmmaVg@mail.gmail.com>
References: <CAEf1y-oUFNMqyF9CVbQtnP9Y7fnQKKZsUy_KagvuLAP3HKjgVA@mail.gmail.com>
	<CAOv69sY9zGzTm7y-xZZx9rDDt5giHZUBz3XNEg3NPpryWCEksQ@mail.gmail.com>
	<4F0D635B.2060004@pearwood.info>
	<CAOv69saboAmaGMhXJ+tfEN6h0XGEtOvivpfO489UE9eW1uLCJw@mail.gmail.com>
	<CAKLa6jSSti+1voXWdSMGwCmJXBS2PdFuKKzdFwoaT3NaOYHZWg@mail.gmail.com>
	<CALXKb5Ptbcedb72YaQT1LToksRCYknEUUkrrBTcPmWwsbmmaVg@mail.gmail.com>
Message-ID: <CAKLa6jSoK_9zsqnGRLoYwLnn_hpLtqjZjm-wR8kH96Fc5=56Dw@mail.gmail.com>

On 11 January 2012 20:11, Max S. <maxskywalker1 at gmail.com> wrote:
> I believe that line 3 raises an error. ?The because you contained the text
> in single quotes, and then used the same character in 'you're not chris',
> Python believes that you are trying to type "you" re not chris". ?You can
> change the single quotes surrounding your string to double quotes ("you're
> not chris"), triple-single quotes ('''you're not chris'''), or triple-double
> quotes ("""you're not chris"""), or you can tell Python that you want to
> include the apostrophe in your string by preceding it with a \ ('you\'re not
> chris'). ?The latter works on the same idea as \n and \t.
>
How didn't I see that?
It just goes to show a gooddun from a baddun.
Cheers
Col

From marco.vincenzo at gmail.com  Wed Jan 11 14:59:30 2012
From: marco.vincenzo at gmail.com (Marco Casazza)
Date: Wed, 11 Jan 2012 08:59:30 -0500
Subject: [Tutor] Is there a better way?
In-Reply-To: <CAPM-O+y2kAxj8tyKCYEhponYAGHbet-ObfLbJq+NNyzd4htVxg@mail.gmail.com>
References: <4F0D81ED.6070103@gmail.com>
	<CAPM-O+y2kAxj8tyKCYEhponYAGHbet-ObfLbJq+NNyzd4htVxg@mail.gmail.com>
Message-ID: <4F0D95C2.50303@gmail.com>

On 2012-01-11 07:57, Joel Goldstick wrote:
> On Wed, Jan 11, 2012 at 7:34 AM, Marco Casazza<marco.vincenzo at gmail.com>  wrote:
>> Hello,
>>
>> I've been slowly teaching myself python, using it for small projects when it
>> seems appropriate. In this case, I was handed a list of email addresses for
>> a mailing but some of them had been truncated. There are only 21 possible
>> email "suffixes" so I planned to just identify which it should be and then
>> replace it. However, when I started writing the code I realized that I'd be
>> doing a lot of "repeating". Is there a better way to "fix" the suffixes
>> without doing each individually? Here's my working code (for 4 colleges):
>>
>> import re
>> with file('c:\python27\mvc\mailing_list.txt', 'r') as infile:
>>     outlist = []
>>     for line in infile.read().split('\n'):
>>         if line.rstrip().lower().endswith('edu'):
>>             newline = line + '\n'
>>             outlist.append(newline.lower())
>>         elif re.search("@bar", line):
>>             newline = re.sub("@bar.*", "@baruch.cuny.edu", line)+'\n'
>>             outlist.append(newline.lower())
>>         elif re.search("@bcc", line):
>>             newline = re.sub("@bcc.*", "@bcc.cuny.edu", line)+'\n'
>>             outlist.append(newline.lower())
>>         elif re.search("@bmc", line):
>>             newline = re.sub("@bmc.*", "@bmcc.cuny.edu", line)+'\n'
>>             outlist.append(newline.lower())
>>         elif re.search("@leh", line):
>>             newline = re.sub("@leh.*", "@lehman.cuny.edu", line)+'\n'
>>             outlist.append(newline.lower())
>>
>> with file('c:\python27\mvc\output.txt','w') as outfile:
>>     outfile.writelines(outlist)
>>
>> Thanks,
>> Marco
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
> First, look here about reading files:
> http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects
>
> I like this better:
>      f = open('filename', 'r')
>      for line in f:
>          print line     # this will give you one line at a time without
> the trailing newline
>
> Second, make a dictionary of with the key being what comes after the @
> in your truncated file.  The value will be the complete text you want:
>   d = {"bcc" : "bcc.cuny.edu", etc. }
>
> Third, use line.split('@') to split the line into what comes before
> and after the @ sign.  It will return a list
>      address_parts = line.split('@')
>
> address_parts[0] is what you want to keep as is. I'm guessing that the
> 3 characters after the @ will be enough to identify what the full
> address should look like, so
> if address_parts[1][0:3] in d:
>    result = '@'.join([address_parts[0], d[address_parts[1][0:3]])
>
> write the result to your out file.
>
> Its early in the morning for me, and this is untested, but it might
> give you some ideas.
>
Hi Joel,

Thanks. I like the dictionary idea... I hadn't thought of that because I 
was trying to fix one "problem" and then realized I had more, and then 
yet more, so it just kept growing--a case of not seeing the forest for 
the trees. And, if I split the address at the amphora I wouldn't need to 
worry about where exactly it was truncated, so no regular expressions to 
gather up the remaining characters after the key.

Thanks again,
Marco

From stognera at gmail.com  Wed Jan 11 17:20:37 2012
From: stognera at gmail.com (Adam Stogner)
Date: Wed, 11 Jan 2012 11:20:37 -0500
Subject: [Tutor] Extremely simple question
In-Reply-To: <CAKLa6jSoK_9zsqnGRLoYwLnn_hpLtqjZjm-wR8kH96Fc5=56Dw@mail.gmail.com>
References: <CAEf1y-oUFNMqyF9CVbQtnP9Y7fnQKKZsUy_KagvuLAP3HKjgVA@mail.gmail.com>
	<CAOv69sY9zGzTm7y-xZZx9rDDt5giHZUBz3XNEg3NPpryWCEksQ@mail.gmail.com>
	<4F0D635B.2060004@pearwood.info>
	<CAOv69saboAmaGMhXJ+tfEN6h0XGEtOvivpfO489UE9eW1uLCJw@mail.gmail.com>
	<CAKLa6jSSti+1voXWdSMGwCmJXBS2PdFuKKzdFwoaT3NaOYHZWg@mail.gmail.com>
	<CALXKb5Ptbcedb72YaQT1LToksRCYknEUUkrrBTcPmWwsbmmaVg@mail.gmail.com>
	<CAKLa6jSoK_9zsqnGRLoYwLnn_hpLtqjZjm-wR8kH96Fc5=56Dw@mail.gmail.com>
Message-ID: <CAE30D0qRUttAXJCDudqGqYOcs7h+=siT8Bh=+MGu_Gd-OPOZYw@mail.gmail.com>

You should be using double quotes on this line and you are missing the last
quote:

print 'You're not Chris!

Should be:

print "You're not Chris!"


On Wed, Jan 11, 2012 at 8:17 AM, col speed <ajarncolin at gmail.com> wrote:

> On 11 January 2012 20:11, Max S. <maxskywalker1 at gmail.com> wrote:
> > I believe that line 3 raises an error.  The because you contained the
> text
> > in single quotes, and then used the same character in 'you're not chris',
> > Python believes that you are trying to type "you" re not chris".  You can
> > change the single quotes surrounding your string to double quotes
> ("you're
> > not chris"), triple-single quotes ('''you're not chris'''), or
> triple-double
> > quotes ("""you're not chris"""), or you can tell Python that you want to
> > include the apostrophe in your string by preceding it with a \ ('you\'re
> not
> > chris').  The latter works on the same idea as \n and \t.
> >
> How didn't I see that?
> It just goes to show a gooddun from a baddun.
> Cheers
> Col
> _______________________________________________
> 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/20120111/b0014044/attachment.html>

From coolankur2006 at gmail.com  Thu Jan 12 13:39:22 2012
From: coolankur2006 at gmail.com (ANKUR AGGARWAL)
Date: Thu, 12 Jan 2012 18:09:22 +0530
Subject: [Tutor] Continuous Shooting
Message-ID: <CAKZ9t5e0-BFPKT1P7wDDJEH-_4UXMheyM355CSPPkkixpGnh9A@mail.gmail.com>

Hey
I was making a demo shooting game and problem is that I want
a continuous stream of bullets. As of now on pressing the space key only
one bullet comes out of the plane (I want this to be continuous stream). On
pressing space key again bullet starts from its initial point. My problem
in the code is that I am able to make a single object of Bullet only (thats
why it is throwing single bullet) and unable to find the another logic.
Please help me out. Attaching the files along with this mail.

import pygame
from pygame.locals import *
import random

pygame.init()
screen=pygame.display.set_mode((640,480),0,24)
pygame.display.set_caption("Hit The Stone")

class Plane(pygame.sprite.Sprite):
    def __init__(self,bullet):
        self.bullet=bullet
        pygame.sprite.Sprite.__init__(self)
        self.image=pygame.image.load('plane.gif').convert()
        self.rect=self.image.get_rect()
        self.rect.centerx=random.randint(0,screen.get_width())
        self.distancefromcenter=30
        self.rect.centery=screen.get_height()-self.distancefromcenter
        self.dx=2
        self.dy=2

    def update(self):
        pressed=pygame.key.get_pressed()
        if pressed[K_DOWN]:
            self.rect.centery+=self.dy
        elif pressed[K_UP]:
            self.rect.centery-=self.dy
        elif pressed[K_LEFT]:
            self.rect.centerx-=self.dx
        elif pressed[K_RIGHT]:
            self.rect.centerx+=self.dx


        if self.rect.bottom>=screen.get_height():
            self.rect.bottom=screen.get_height()
        elif self.rect.top<=0:
            self.rect.top=0

        if self.rect.centerx>=screen.get_width()-self.distancefromcenter:
            self.rect.centerx=screen.get_width()-self.distancefromcenter
        elif self.rect.centerx<=self.distancefromcenter:
            self.rect.centerx=self.distancefromcenter

        if pressed[K_SPACE]:
            self.bullet.x=self.rect.centerx
            self.bullet.y=self.rect.centery



class Bullet(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image=pygame.image.load('geometrybullet.png').convert_alpha()
        self.rect=self.image.get_rect()
        self.rect.center=(-100,-100)
        self.x=-100
        self.y=-100
        self.dy=5


    def update(self):
        self.y-=self.dy
        self.rect.center=(self.x,self.y)
        if self.rect.top<0:
            self.x=-100
            self.y=-100


def main():
    background=pygame.Surface(screen.get_size())
    background=background.convert()
    screen.blit(background,(0,0))
    bullet=Bullet()
    plane=Plane(bullet)
    allSprites=pygame.sprite.Group(plane,bullet)

    while 1:
        for i in pygame.event.get():
            quitPressed=pygame.key.get_pressed()
            if i.type==QUIT or quitPressed[K_q]:
                exit()

        allSprites.clear(screen,background)
        allSprites.update()
        allSprites.draw(screen)
        pygame.display.flip()


if __name__=='__main__':
    main()

Thanks in advance :)

Regards
Ankur Aggarwal
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120112/6f0da1c5/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: geometrybullet.png
Type: image/png
Size: 273 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120112/6f0da1c5/attachment.png>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: plane.gif
Type: image/gif
Size: 1899 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120112/6f0da1c5/attachment.gif>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: game.py
Type: text/x-python
Size: 2580 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120112/6f0da1c5/attachment.py>

From hugo.yoshi at gmail.com  Thu Jan 12 14:39:20 2012
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Thu, 12 Jan 2012 14:39:20 +0100
Subject: [Tutor] Continuous Shooting
In-Reply-To: <CAKZ9t5e0-BFPKT1P7wDDJEH-_4UXMheyM355CSPPkkixpGnh9A@mail.gmail.com>
References: <CAKZ9t5e0-BFPKT1P7wDDJEH-_4UXMheyM355CSPPkkixpGnh9A@mail.gmail.com>
Message-ID: <CAJmBOf=8UonTt0GBBAbxc-jc8dLxzmD43RQZ=6rSugmFYrzMHg@mail.gmail.com>

On Thu, Jan 12, 2012 at 1:39 PM, ANKUR AGGARWAL <coolankur2006 at gmail.com> wrote:
> Hey
> I was making a demo shooting game and problem is that I want
> a?continuous?stream of bullets. As of now on pressing the space key only one
> bullet comes out of the plane (I want this to be?continuous?stream). On
> pressing space key again bullet starts from its initial point. My problem in
> the code is that I am able to make a single object of Bullet only (thats why
> it is throwing single bullet) and unable to find the another logic. Please
> help me out. Attaching the files along with this mail.
>

Well, the solution seems like it should be simple. Right now, you
create a single bullet object and associate it with the plane, then
you center the bullet on the plane when you press spacebar. What you
should do instead is create a new bullet object every time the
spacebar is pressed (or, alternatively, create a new one every so
often while the spacebar is held down). I'd suggest you keep a
separate sprite group for all bullets, and put it in a place where all
your classes can access it (at the module level seems like a good
idea).

Oh, and do keep in mind that if you do pygame.image.load() every time
you make a new bullet, you will have the same image in memory multiple
times, which is quite wasteful. Instead, you should load it once and
reuse the same image for all your Bullets.

HTH,
Hugo

From 0101amt at gmail.com  Thu Jan 12 15:24:59 2012
From: 0101amt at gmail.com (amt)
Date: Thu, 12 Jan 2012 09:24:59 -0500
Subject: [Tutor] Are there other ways of solving this exercise?
Message-ID: <CAEQEn02=VpVxKXRJvzPMpd=+J8mv3cQs4o0Ep20g_08Ov5p5tQ@mail.gmail.com>

Exercise 16, extra credit 3: There's too much repetition in this file.
Use strings, formats, and escapes to print out line1, line2, and line3
with just one target.write() command instead of 6.
Code from the book:


from sys import argv

script, filename = argv

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename,'w')

print "Truncating the file. Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print "And finally, we close it."
target.close()




How I solved it after trial and error:

from sys import argv

script, filename = argv

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file. Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write("%s\n%s\n%s\n" %(line1, line2, line3))

print "And finally, we close it."
target.close()

This is the only method I was able to figure out of solving the exercise.

Are there other ways of solving this exercise using strings, formats
and escapes like the author mentioned in the exercise question? If
yes, please write them.




Regards,amt.

From lina.lastname at gmail.com  Thu Jan 12 15:38:23 2012
From: lina.lastname at gmail.com (lina)
Date: Thu, 12 Jan 2012 22:38:23 +0800
Subject: [Tutor] append index out of range
Message-ID: <CAG9cJmkd991PXrewQLMh0OzQe0O1A=AQcr8+0zPfrQCLzkJcqA@mail.gmail.com>

Hi,

there is a file

$ cat atom-pair_9.out | wc -l
75426

there is 75426 lines there,

    results=[]
    unique={}
    for line in open(tobetranslatedfile,"r"):
        tobetranslatedparts=line.strip().split()
        results.append(dictionary[tobetranslatedparts[2]])

it complains

    results.append(dictionary[tobetranslatedparts[2]])
IndexError: list index out of range


is it really too large this file?

Thanks,

From wprins at gmail.com  Thu Jan 12 15:40:26 2012
From: wprins at gmail.com (Walter Prins)
Date: Thu, 12 Jan 2012 14:40:26 +0000
Subject: [Tutor] Are there other ways of solving this exercise?
In-Reply-To: <CAEQEn02=VpVxKXRJvzPMpd=+J8mv3cQs4o0Ep20g_08Ov5p5tQ@mail.gmail.com>
References: <CAEQEn02=VpVxKXRJvzPMpd=+J8mv3cQs4o0Ep20g_08Ov5p5tQ@mail.gmail.com>
Message-ID: <CANLXbfCpUyDvsP92TiT-NvRMaBL=EF5avAEMgbSkZZ6SPAi4jg@mail.gmail.com>

Hi,

On 12 January 2012 14:24, amt <0101amt at gmail.com> wrote:
>
> target.write("%s\n%s\n%s\n" %(line1, line2, line3))
>
> This is the only method I was able to figure out of solving the exercise.
>
> Are there other ways of solving this exercise using strings, formats
> and escapes like the author mentioned in the exercise question? If
> yes, please write them.


Firstly for those interested, I've tracked this down to "Learn Python
The Hard Way, 2nd Edition".? (Amt, please include a reference if
possible (especially when online) when you ask questions.)? The
question is available here:
http://learnpythonthehardway.org/book/ex16.html

As for your question, I suppose using the string.format() method is
another way that involves "strings, formats and escapes".? See here:
http://docs.python.org/library/stdtypes.html? (and see the section on
str.format therein. )

Walter

From wprins at gmail.com  Thu Jan 12 15:42:21 2012
From: wprins at gmail.com (Walter Prins)
Date: Thu, 12 Jan 2012 14:42:21 +0000
Subject: [Tutor] append index out of range
In-Reply-To: <CAG9cJmkd991PXrewQLMh0OzQe0O1A=AQcr8+0zPfrQCLzkJcqA@mail.gmail.com>
References: <CAG9cJmkd991PXrewQLMh0OzQe0O1A=AQcr8+0zPfrQCLzkJcqA@mail.gmail.com>
Message-ID: <CANLXbfB-X-56oe2LUT4-eN_cgnjLGN7yAbVJs77AXkgRnYUh7g@mail.gmail.com>

Hi

On 12 January 2012 14:38, lina <lina.lastname at gmail.com> wrote:
> Hi,
>
> there is a file
>
> $ cat atom-pair_9.out | wc -l
> 75426
>
> there is 75426 lines there,
>
> ? ?results=[]
> ? ?unique={}
> ? ?for line in open(tobetranslatedfile,"r"):
> ? ? ? ?tobetranslatedparts=line.strip().split()
> ? ? ? ?results.append(dictionary[tobetranslatedparts[2]])
>
> it complains
>
> ? ?results.append(dictionary[tobetranslatedparts[2]])
> IndexError: list index out of range
>
>
> is it really too large this file?

Read the error message more carefully.  (Hint: It's not saying
anything about the file at all...)

Walter

From bgailer at gmail.com  Thu Jan 12 15:48:33 2012
From: bgailer at gmail.com (bob gailer)
Date: Thu, 12 Jan 2012 09:48:33 -0500
Subject: [Tutor] append index out of range
In-Reply-To: <CAG9cJmkd991PXrewQLMh0OzQe0O1A=AQcr8+0zPfrQCLzkJcqA@mail.gmail.com>
References: <CAG9cJmkd991PXrewQLMh0OzQe0O1A=AQcr8+0zPfrQCLzkJcqA@mail.gmail.com>
Message-ID: <4F0EF2C1.7090000@gmail.com>

On 1/12/2012 9:38 AM, lina wrote:
> Hi,
>
> there is a file
>
> $ cat atom-pair_9.out | wc -l
> 75426
>
> there is 75426 lines there,
>
>      results=[]
>      unique={}
>      for line in open(tobetranslatedfile,"r"):
>          tobetranslatedparts=line.strip().split()
>          results.append(dictionary[tobetranslatedparts[2]])
>
> it complains
>
>      results.append(dictionary[tobetranslatedparts[2]])
> IndexError: list index out of range
>
>
> is it really too large this file?

This has nothing to do with the size of the file. It means Python 
encountered a line in the file with less than 3 
"whitespace-separated-tokens".

List indexing starts at 0, so tobetranslatedparts[2] refers to the 3rd 
item of the list that was created by split().

If that does not help, please show us some sample lines.




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


From d at davea.name  Thu Jan 12 15:56:22 2012
From: d at davea.name (Dave Angel)
Date: Thu, 12 Jan 2012 09:56:22 -0500
Subject: [Tutor] append index out of range
In-Reply-To: <CAG9cJmkd991PXrewQLMh0OzQe0O1A=AQcr8+0zPfrQCLzkJcqA@mail.gmail.com>
References: <CAG9cJmkd991PXrewQLMh0OzQe0O1A=AQcr8+0zPfrQCLzkJcqA@mail.gmail.com>
Message-ID: <4F0EF496.2080201@davea.name>

On 01/12/2012 09:38 AM, lina wrote:
> Hi,
>
> there is a file
>
> $ cat atom-pair_9.out | wc -l
> 75426
>
> there is 75426 lines there,
>
>      results=[]
>      unique={}
>      for line in open(tobetranslatedfile,"r"):
>          tobetranslatedparts=line.strip().split()
>          results.append(dictionary[tobetranslatedparts[2]])
>
> it complains
>
>      results.append(dictionary[tobetranslatedparts[2]])
> IndexError: list index out of range
>
>
> is it really too large this file?
>
This problem has nothing to do with the size of the file, nor with append().

You've got a lot going on in that line.  To solve an error message on a 
complex line, decompose it, either with extra prints, or with a literal 
decomposition into separate variables.

Personally, I'd start with a print of the tobetranslatedparts variable.  
it is a list, after all, and the error message is complaining about a 
list index.

Then, when it has printed out many lists, figure out what's different 
about the last one, the one that triggered the error.

Once you've figured out what's wrong with that line, figure out how to 
deal with it.  Does it mean the file is invalid?  Or does it mean your 
loop has to be somewhat more complex?

-- 

DaveA


From 0101amt at gmail.com  Thu Jan 12 16:11:23 2012
From: 0101amt at gmail.com (amt)
Date: Thu, 12 Jan 2012 10:11:23 -0500
Subject: [Tutor] Are there other ways of solving this exercise?
In-Reply-To: <CANLXbfCpUyDvsP92TiT-NvRMaBL=EF5avAEMgbSkZZ6SPAi4jg@mail.gmail.com>
References: <CAEQEn02=VpVxKXRJvzPMpd=+J8mv3cQs4o0Ep20g_08Ov5p5tQ@mail.gmail.com>
	<CANLXbfCpUyDvsP92TiT-NvRMaBL=EF5avAEMgbSkZZ6SPAi4jg@mail.gmail.com>
Message-ID: <CAEQEn034PQ08EGQmXjCRA_841YSXxXHOU0_iwLfbeHSVc=xf3g@mail.gmail.com>

On Thu, Jan 12, 2012 at 9:40 AM, Walter Prins <wprins at gmail.com> wrote:
> Hi,
>
> On 12 January 2012 14:24, amt <0101amt at gmail.com> wrote:
>>
>> target.write("%s\n%s\n%s\n" %(line1, line2, line3))
>>
>> This is the only method I was able to figure out of solving the exercise.
>>
>> Are there other ways of solving this exercise using strings, formats
>> and escapes like the author mentioned in the exercise question? If
>> yes, please write them.
>
>
> Firstly for those interested, I've tracked this down to "Learn Python
> The Hard Way, 2nd Edition".? (Amt, please include a reference if
> possible (especially when online) when you ask questions.)? The
> question is available here:
> http://learnpythonthehardway.org/book/ex16.html
>
> As for your question, I suppose using the string.format() method is
> another way that involves "strings, formats and escapes".? See here:
> http://docs.python.org/library/stdtypes.html? (and see the section on
> str.format therein. )
>
> Walter

Ok, I will keep that in mind.



After reading from http://docs.python.org/library/stdtypes.html I came
up with this:

from sys import argv

script, filename = argv

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file. Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

bag = "%s\n%s\n%s\n".format(line1,line2,line3)
target.write(bag)

print "And finally, we close it."
target.close()


Is this how it is supposed to look like using str.format?




Thanks,amt.

From wprins at gmail.com  Thu Jan 12 16:26:03 2012
From: wprins at gmail.com (Walter Prins)
Date: Thu, 12 Jan 2012 15:26:03 +0000
Subject: [Tutor] Are there other ways of solving this exercise?
In-Reply-To: <CAEQEn034PQ08EGQmXjCRA_841YSXxXHOU0_iwLfbeHSVc=xf3g@mail.gmail.com>
References: <CAEQEn02=VpVxKXRJvzPMpd=+J8mv3cQs4o0Ep20g_08Ov5p5tQ@mail.gmail.com>
	<CANLXbfCpUyDvsP92TiT-NvRMaBL=EF5avAEMgbSkZZ6SPAi4jg@mail.gmail.com>
	<CAEQEn034PQ08EGQmXjCRA_841YSXxXHOU0_iwLfbeHSVc=xf3g@mail.gmail.com>
Message-ID: <CANLXbfAHcdwpkmDzoknh4CzYJn1y1MDURe8QRmVpBPSYhUaQQw@mail.gmail.com>

Hi amt,

On 12 January 2012 15:11, amt <0101amt at gmail.com> wrote:
> After reading from http://docs.python.org/library/stdtypes.html I came
> up with this:
>
> bag = "%s\n%s\n%s\n".format(line1,line2,line3)
> target.write(bag)
>
> Is this how it is supposed to look like using str.format?

Not quite.  The documentation states:

"str.format(*args, **kwargs): Perform a string formatting operation.
The string on which this method is called can contain literal text or
replacement fields delimited by braces {}. Each replacement field
contains either the numeric index of a positional argument, or the
name of a keyword argument. Returns a copy of the string where each
replacement field is replaced with the string value of the
corresponding argument."

So, this is different from the % operator, where format specifiers are
indicated with %.  Instead you need to use, as per the documentation,
curly braces e.g. {  and }.

You can easily test this in the Python interpreter e.g.:

>>> print "%s\n%s\n%s".format('aaa', 'bbb', 'ccc')
%s
%s
%s

(Hmm, does not work...)

>>> print '{0}\n{1}\n{2}'.format('aaa','bbb','ccc')
aaa
bbb
ccc

(Hmm, that does work!...)

Final comment, you can get rid of the variable "bag" by directly
printing the result of the call to format() like you did in your
previous solution.

Cheers,

Walter

From msg.ufo at gmail.com  Thu Jan 12 16:43:36 2012
From: msg.ufo at gmail.com (Mike G)
Date: Thu, 12 Jan 2012 07:43:36 -0800
Subject: [Tutor]  Are there other ways of solving this exercise?
Message-ID: <CAHD43mpn51YhCKUTUXvmt9occAC38ALiuY674p0CLSDPMsF7UQ@mail.gmail.com>

<quote>
...Exercise 16, extra credit 3...Code from the book...like the author mentioned
</quote>

The book and author, do they have a name...? Is this an exercise in refactoring?

From lina.lastname at gmail.com  Thu Jan 12 16:50:04 2012
From: lina.lastname at gmail.com (lina)
Date: Thu, 12 Jan 2012 23:50:04 +0800
Subject: [Tutor] append index out of range
In-Reply-To: <4F0EF496.2080201@davea.name>
References: <CAG9cJmkd991PXrewQLMh0OzQe0O1A=AQcr8+0zPfrQCLzkJcqA@mail.gmail.com>
	<4F0EF496.2080201@davea.name>
Message-ID: <CAG9cJmmcVYa8reqhG9OQtAQ-eVt0iyOjdA6dvE-ciJfFtf+rzg@mail.gmail.com>

On Thu, Jan 12, 2012 at 10:56 PM, Dave Angel <d at davea.name> wrote:
> On 01/12/2012 09:38 AM, lina wrote:
>>
>> Hi,
>>
>> there is a file
>>
>> $ cat atom-pair_9.out | wc -l
>> 75426
>>
>> there is 75426 lines there,
>>
>> ? ? results=[]
>> ? ? unique={}
>> ? ? for line in open(tobetranslatedfile,"r"):
>> ? ? ? ? tobetranslatedparts=line.strip().split()
>> ? ? ? ? results.append(dictionary[tobetranslatedparts[2]])
>>
>> it complains
>>
>> ? ? results.append(dictionary[tobetranslatedparts[2]])
>> IndexError: list index out of range
>>
>>
>> is it really too large this file?
>>
> This problem has nothing to do with the size of the file, nor with append().

Thanks all.
I am really not experienced.

>
> You've got a lot going on in that line. ?To solve an error message on a
> complex line, decompose it, either with extra prints, or with a literal
> decomposition into separate variables.
>
> Personally, I'd start with a print of the tobetranslatedparts variable. ?it
> is a list, after all, and the error message is complaining about a list
> index.

The file I tried there is one line only one field. and the file was
still writing, not finished yet. I was so careless.

>
> Then, when it has printed out many lists, figure out what's different about
> the last one, the one that triggered the error.
>
> Once you've figured out what's wrong with that line, figure out how to deal
> with it. ?Does it mean the file is invalid? ?Or does it mean your loop has
> to be somewhat more complex?

The file is invalid.

Thanks again, I will try once it's finished.

>
> --
>
> DaveA
>

From 0101amt at gmail.com  Thu Jan 12 17:57:21 2012
From: 0101amt at gmail.com (amt)
Date: Thu, 12 Jan 2012 11:57:21 -0500
Subject: [Tutor] Are there other ways of solving this exercise?
In-Reply-To: <CANLXbfAHcdwpkmDzoknh4CzYJn1y1MDURe8QRmVpBPSYhUaQQw@mail.gmail.com>
References: <CAEQEn02=VpVxKXRJvzPMpd=+J8mv3cQs4o0Ep20g_08Ov5p5tQ@mail.gmail.com>
	<CANLXbfCpUyDvsP92TiT-NvRMaBL=EF5avAEMgbSkZZ6SPAi4jg@mail.gmail.com>
	<CAEQEn034PQ08EGQmXjCRA_841YSXxXHOU0_iwLfbeHSVc=xf3g@mail.gmail.com>
	<CANLXbfAHcdwpkmDzoknh4CzYJn1y1MDURe8QRmVpBPSYhUaQQw@mail.gmail.com>
Message-ID: <CAEQEn03Yr9o3a+vW4W+aFU4NhXiTHN=A++F-4gpzhfPOX4X-4A@mail.gmail.com>

I'll give it another try:

On Thu, Jan 12, 2012 at 10:26 AM, Walter Prins <wprins at gmail.com> wrote:
> Hi amt,
>
> On 12 January 2012 15:11, amt <0101amt at gmail.com> wrote:
>> After reading from http://docs.python.org/library/stdtypes.html I came
>> up with this:
>>
>> bag = "%s\n%s\n%s\n".format(line1,line2,line3)
>> target.write(bag)
>>
>> Is this how it is supposed to look like using str.format?
>
> Not quite. ?The documentation states:
>
> "str.format(*args, **kwargs): Perform a string formatting operation.
> The string on which this method is called can contain literal text or
> replacement fields delimited by braces {}. Each replacement field
> contains either the numeric index of a positional argument, or the
> name of a keyword argument. Returns a copy of the string where each
> replacement field is replaced with the string value of the
> corresponding argument."
>
> So, this is different from the % operator, where format specifiers are
> indicated with %. ?Instead you need to use, as per the documentation,
> curly braces e.g. { ?and }.
>
> You can easily test this in the Python interpreter e.g.:
>
>>>> print "%s\n%s\n%s".format('aaa', 'bbb', 'ccc')
> %s
> %s
> %s
>
> (Hmm, does not work...)
>
>>>> print '{0}\n{1}\n{2}'.format('aaa','bbb','ccc')
> aaa
> bbb
> ccc
>
> (Hmm, that does work!...)
So the code should look like this:

bag = "{0}\n{1}\n{2}".format(line1,line2,line3)
target.write(bag)



>
> Final comment, you can get rid of the variable "bag" by directly
> printing the result of the call to format() like you did in your
> previous solution.
>
> Cheers,
>
> Walter

You mean print "{0}\n{1}\n{2}\n".format(line1,line2,line3)?


Ok, but if I drop the variable bag and print directly,how will I write
line1,line2,line3 in the .txt file since I have no parameter to give
to the write method.(target.write() ) ?


Walter, thanks a lot for taking your time to help me out.




Cheers, amt.

From coolankur2006 at gmail.com  Thu Jan 12 18:31:18 2012
From: coolankur2006 at gmail.com (ANKUR AGGARWAL)
Date: Thu, 12 Jan 2012 23:01:18 +0530
Subject: [Tutor] Delay Between iterations
Message-ID: <CAKZ9t5cBOzX-7x1Fa7pw7vjreWRwKTa5HSrvDVGbA=rbmA7VRw@mail.gmail.com>

import pygame
from pygame.locals import *
import random

pygame.init()
screen=pygame.display.set_mode((640,480),0,24)
pygame.display.set_caption("Hit The Stone")
background=pygame.Surface(screen.get_size())
background=background.convert()
screen.blit(background,(0,0))

class Plane(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image=pygame.image.load('plane.gif').convert()
        self.rect=self.image.get_rect()
        self.rect.centerx=random.randint(0,screen.get_width())
        self.distancefromcenter=30
        self.rect.centery=screen.get_height()-self.distancefromcenter
        self.dx=2
        self.dy=2

    def update(self):
        self.pressed=pygame.key.get_pressed()
        if self.pressed[K_DOWN]:
            self.rect.centery+=self.dy
        elif self.pressed[K_UP]:
            self.rect.centery-=self.dy
        elif self.pressed[K_LEFT]:
            self.rect.centerx-=self.dx
        elif self.pressed[K_RIGHT]:
            self.rect.centerx+=self.dx


        if self.rect.bottom>=screen.get_height():
            self.rect.bottom=screen.get_height()
        elif self.rect.top<=0:
            self.rect.top=0

        if self.rect.centerx>=screen.get_width()-self.distancefromcenter:
            self.rect.centerx=screen.get_width()-self.distancefromcenter
        elif self.rect.centerx<=self.distancefromcenter:
            self.rect.centerx=self.distancefromcenter




class Bullet(pygame.sprite.Sprite):
    def __init__(self,posx,posy,image):
        pygame.sprite.Sprite.__init__(self)
        if self.shootCount>10:
            self.image=image
            self.rect=self.image.get_rect()
            self.rect.center=(posx,posy-30)
            self.dy=5
        else:
            self.shootCount+=1


    def update(self):
        self.rect.centery-=self.dy
        self.rect.center=(self.rect.centerx,self.rect.centery)
        if self.rect.top<=0:
            self.kill()


def main():
    image=pygame.image.load('geometrybullet.png').convert()
    plane=Plane()
    allSprites=pygame.sprite.Group(plane)
    clock=pygame.time.Clock()

    while 1:
        pressed=pygame.key.get_pressed()
        for i in pygame.event.get():
            if i.type==QUIT or pressed[K_q]:
                exit()
*        if  pressed[K_SPACE]:*
*                bullet=Bullet(plane.rect.centerx,plane.rect.centery,image)*
*                bullet.shootCount=0*
*                allSprites.add(bullet)*


        allSprites.clear(screen,background)
        allSprites.update()
        allSprites.draw(screen)
        pygame.display.flip()


if __name__=='__main__':
    main()


I was trying to make shooting game. whenever I press the space key bullet
object is called (bold code) . I want delay between iterations to produce
the gap between the bullets.Tried the time.wait() but its working. Any
Ideas??

Thanks In Advance

Regards
Ankur Aggarwal
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120112/6b73f6fc/attachment.html>

From coolankur2006 at gmail.com  Thu Jan 12 18:35:12 2012
From: coolankur2006 at gmail.com (ANKUR AGGARWAL)
Date: Thu, 12 Jan 2012 23:05:12 +0530
Subject: [Tutor] Delay Between iterations
In-Reply-To: <CAKZ9t5cBOzX-7x1Fa7pw7vjreWRwKTa5HSrvDVGbA=rbmA7VRw@mail.gmail.com>
References: <CAKZ9t5cBOzX-7x1Fa7pw7vjreWRwKTa5HSrvDVGbA=rbmA7VRw@mail.gmail.com>
Message-ID: <CAKZ9t5fJHDf1y4a5d13t9u6CZpzf4QVHg4pDP3yNBxo2c2DFJg@mail.gmail.com>

In the last code provided I messed up the Bullet Class Code. Apologies for
that. Below is my code :

import pygame
from pygame.locals import *
import random
import time

pygame.init()
screen=pygame.display.set_mode((640,480),0,24)
pygame.display.set_caption("Hit The Stone")
background=pygame.Surface(screen.get_size())
background=background.convert()
screen.blit(background,(0,0))

class Plane(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image=pygame.image.load('plane.gif').convert()
        self.rect=self.image.get_rect()
        self.rect.centerx=random.randint(0,screen.get_width())
        self.distancefromcenter=30
        self.rect.centery=screen.get_height()-self.distancefromcenter
        self.dx=2
        self.dy=2

    def update(self):
        self.pressed=pygame.key.get_pressed()
        if self.pressed[K_DOWN]:
            self.rect.centery+=self.dy
        elif self.pressed[K_UP]:
            self.rect.centery-=self.dy
        elif self.pressed[K_LEFT]:
            self.rect.centerx-=self.dx
        elif self.pressed[K_RIGHT]:
            self.rect.centerx+=self.dx


        if self.rect.bottom>=screen.get_height():
            self.rect.bottom=screen.get_height()
        elif self.rect.top<=0:
            self.rect.top=0

        if self.rect.centerx>=screen.get_width()-self.distancefromcenter:
            self.rect.centerx=screen.get_width()-self.distancefromcenter
        elif self.rect.centerx<=self.distancefromcenter:
            self.rect.centerx=self.distancefromcenter




class Bullet(pygame.sprite.Sprite):
    def __init__(self,posx,posy,image):
        pygame.sprite.Sprite.__init__(self)
        self.image=image
        self.rect=self.image.get_rect()
        self.rect.center=(posx,posy-30)
        self.dy=5



    def update(self):
        self.rect.centery-=self.dy
        self.rect.center=(self.rect.centerx,self.rect.centery)
        if self.rect.top<=0:
            self.kill()
class Blank(pygame.sprite.Sprite):
    def __init__(self,posx,posy):
        pygame.sprite.Sprite.__init__(self)
        self.image=pygame.Surface((10,20))
        self.image.fill((0,0,0))
        self.rect=self.image.get_rect()
        self.rect.center=(posx,posy-30)
        self.dy=5


    def update(self):
        self.rect.centery-=self.dy
        self.rect.center=(self.rect.centerx,self.rect.centery)
        if self.rect.top<=0:
            self.kill()


def main():
    image=pygame.image.load('geometrybullet.png').convert()
    plane=Plane()
    allSprites=pygame.sprite.Group(plane)
    clock=pygame.time.Clock()

    while 1:
        pressed=pygame.key.get_pressed()
        for i in pygame.event.get():
            if i.type==QUIT or pressed[K_q]:
                exit()
        if  pressed[K_SPACE]:
                bullet=Bullet(plane.rect.centerx,plane.rect.centery,image)
                bullet.shootCount=0
                allSprites.add(bullet)


        allSprites.clear(screen,background)
        allSprites.update()
        allSprites.draw(screen)
        pygame.display.flip()


if __name__=='__main__':
    main()



On Thu, Jan 12, 2012 at 11:01 PM, ANKUR AGGARWAL <coolankur2006 at gmail.com>wrote:

> import pygame
> from pygame.locals import *
> import random
>
> pygame.init()
> screen=pygame.display.set_mode((640,480),0,24)
> pygame.display.set_caption("Hit The Stone")
> background=pygame.Surface(screen.get_size())
> background=background.convert()
> screen.blit(background,(0,0))
>
> class Plane(pygame.sprite.Sprite):
>     def __init__(self):
>         pygame.sprite.Sprite.__init__(self)
>         self.image=pygame.image.load('plane.gif').convert()
>         self.rect=self.image.get_rect()
>         self.rect.centerx=random.randint(0,screen.get_width())
>         self.distancefromcenter=30
>         self.rect.centery=screen.get_height()-self.distancefromcenter
>         self.dx=2
>         self.dy=2
>
>     def update(self):
>         self.pressed=pygame.key.get_pressed()
>         if self.pressed[K_DOWN]:
>             self.rect.centery+=self.dy
>         elif self.pressed[K_UP]:
>             self.rect.centery-=self.dy
>         elif self.pressed[K_LEFT]:
>             self.rect.centerx-=self.dx
>         elif self.pressed[K_RIGHT]:
>             self.rect.centerx+=self.dx
>
>
>         if self.rect.bottom>=screen.get_height():
>             self.rect.bottom=screen.get_height()
>         elif self.rect.top<=0:
>             self.rect.top=0
>
>         if self.rect.centerx>=screen.get_width()-self.distancefromcenter:
>             self.rect.centerx=screen.get_width()-self.distancefromcenter
>         elif self.rect.centerx<=self.distancefromcenter:
>             self.rect.centerx=self.distancefromcenter
>
>
>
>
> class Bullet(pygame.sprite.Sprite):
>     def __init__(self,posx,posy,image):
>         pygame.sprite.Sprite.__init__(self)
>         if self.shootCount>10:
>             self.image=image
>             self.rect=self.image.get_rect()
>             self.rect.center=(posx,posy-30)
>             self.dy=5
>         else:
>             self.shootCount+=1
>
>
>     def update(self):
>         self.rect.centery-=self.dy
>         self.rect.center=(self.rect.centerx,self.rect.centery)
>         if self.rect.top<=0:
>             self.kill()
>
>
> def main():
>     image=pygame.image.load('geometrybullet.png').convert()
>     plane=Plane()
>     allSprites=pygame.sprite.Group(plane)
>     clock=pygame.time.Clock()
>
>     while 1:
>         pressed=pygame.key.get_pressed()
>         for i in pygame.event.get():
>             if i.type==QUIT or pressed[K_q]:
>                 exit()
> *        if  pressed[K_SPACE]:*
> *
> bullet=Bullet(plane.rect.centerx,plane.rect.centery,image)*
> *                bullet.shootCount=0*
> *                allSprites.add(bullet)*
>
>
>         allSprites.clear(screen,background)
>         allSprites.update()
>         allSprites.draw(screen)
>         pygame.display.flip()
>
>
> if __name__=='__main__':
>     main()
>
>
> I was trying to make shooting game. whenever I press the space key bullet
> object is called (bold code) . I want delay between iterations to produce
> the gap between the bullets.Tried the time.wait() but its working. Any
> Ideas??
>
> Thanks In Advance
>
> Regards
> Ankur Aggarwal
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120112/72248778/attachment-0001.html>

From defensoft at gmail.com  Thu Jan 12 19:36:35 2012
From: defensoft at gmail.com (Nate Lastname)
Date: Thu, 12 Jan 2012 13:36:35 -0500
Subject: [Tutor] Delay Between iterations
In-Reply-To: <CAKZ9t5fJHDf1y4a5d13t9u6CZpzf4QVHg4pDP3yNBxo2c2DFJg@mail.gmail.com>
References: <CAKZ9t5cBOzX-7x1Fa7pw7vjreWRwKTa5HSrvDVGbA=rbmA7VRw@mail.gmail.com>
	<CAKZ9t5fJHDf1y4a5d13t9u6CZpzf4QVHg4pDP3yNBxo2c2DFJg@mail.gmail.com>
Message-ID: <CABe2FwqsGQH31PChyvMm+Udj4O7QZx7tKmEk0Z0Hb8qdMkmyjw@mail.gmail.com>

Hello ANKUR,

Just add a timer variable to the plane class.  Every time it is
updated, subtract time from the timer.  When it hits 0, the bullet can
be fired.  Else, it cannot.  When the bullet is fired, reset the timer
to a delay value.  It's that simple :)

Cheers,
Nathanael Lastname.

-- 
My Blog - Defenestration Coding

http://defenestrationcoding.wordpress.com/

From wprins at gmail.com  Thu Jan 12 21:52:33 2012
From: wprins at gmail.com (Walter Prins)
Date: Thu, 12 Jan 2012 20:52:33 +0000
Subject: [Tutor] Are there other ways of solving this exercise?
In-Reply-To: <CAEQEn03Yr9o3a+vW4W+aFU4NhXiTHN=A++F-4gpzhfPOX4X-4A@mail.gmail.com>
References: <CAEQEn02=VpVxKXRJvzPMpd=+J8mv3cQs4o0Ep20g_08Ov5p5tQ@mail.gmail.com>
	<CANLXbfCpUyDvsP92TiT-NvRMaBL=EF5avAEMgbSkZZ6SPAi4jg@mail.gmail.com>
	<CAEQEn034PQ08EGQmXjCRA_841YSXxXHOU0_iwLfbeHSVc=xf3g@mail.gmail.com>
	<CANLXbfAHcdwpkmDzoknh4CzYJn1y1MDURe8QRmVpBPSYhUaQQw@mail.gmail.com>
	<CAEQEn03Yr9o3a+vW4W+aFU4NhXiTHN=A++F-4gpzhfPOX4X-4A@mail.gmail.com>
Message-ID: <CANLXbfBzZUBX72RBzxGHZXNCgbdfefkX9fKb+ifCPwgkkO6DrQ@mail.gmail.com>

On 12 January 2012 16:57, amt <0101amt at gmail.com> wrote:
> I'll give it another try:

> So the code should look like this:
>
> bag = "{0}\n{1}\n{2}".format(line1,line2,line3)
> target.write(bag)
>
Yes.

>> Final comment, you can get rid of the variable "bag" by directly
>> printing the result of the call to format() like you did in your
>> previous solution.

> You mean print "{0}\n{1}\n{2}\n".format(line1,line2,line3)?

No, print as such is actually besides the point, it was just used to
actually output the string with some interpretation given to the
newlines.


> Ok, but if I drop the variable bag and print directly,how will I write
> line1,line2,line3 in the .txt file since I have no parameter to give
> to the write method.(target.write() ) ?

Well in fact you do, in the same way that you have one in your
original solution which had no intermediate "bag" variable.

OK let's backtrack a bit and try to clarify.  In your original solution you had:

target.write("%s\n%s\n%s\n" %(line1, line2, line3))

What's happening here?  Firstly you're calculating a string expression, namely:

"%s\n%s\n%s\n" %(line1, line2, line3)

Let's try this in the Python interpreter:

Python 2.7 (r27:82525, Jul  4 2010, 07:43:08) [MSC v.1500 64 bit
(AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> "%s\n%s\n%s\n" % ('aaa','bbb','ccc')
'aaa\nbbb\nccc\n'
>>> print "%s\n%s\n%s\n" % ('aaa','bbb','ccc')
aaa
bbb
ccc

>>>

Notice, first I type the expression directly at the interpreter
prompt.  Python therefore evaluates the epxression types, and as a
courtesy displays the result, then discards it.  On the next line, I
repeat the excercise, but this time prepend a print statement to it.
This is essentially giving the result of the expression evaluation to
the print statement.  Now the job of the print statement is also to
display the value of variables, but it applies a bit more
interpretation to what it's given, and so it actually interpretets the
"newline" characters in the result string, displayed as "\n" in the
string on the previous line, and so the literal "aaa", "bbb" and "ccc"
ends up on seperate lines.

Now consider your original line again:
target.write("%s\n%s\n%s\n" %(line1, line2, line3))

What's actually happening here?  Well, as happens in the interactive
interpreter example above, firstly the string expression using the %
operator is evaluated, which results in a string result as above, but
using the contents of line1, line2 and line3.  This result is then
passed as the parameter to the target.write() method.

Now, the exact same thing happens when you use a string method.  The
string method str.format() also returns a result, namely the string
that results when formatting the format string with the parameter
values specified.  So in this sense it's no different to what you had
before.  Here's an interactive Python demonstration again:

Python 2.7 (r27:82525, Jul  4 2010, 07:43:08) [MSC v.1500 64 bit
(AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> '{0}\n{1}\n{2}\n'.format("aaa","bbb","ccc")
'aaa\nbbb\nccc\n'
>>> print '{0}\n{1}\n{2}\n'.format("aaa","bbb","ccc")
aaa
bbb
ccc

>>>

Notice, the mechanics is exactly the same.  Consequently, you can
write your code without the intermediate "bag" variable, just like you
didn't need it in your original solution:
target.write( '{0}\n{1}\n{2}\n'.format(line1,line2,line3) )

To belabor the point: here the call to str.format() returns a result
(another string) which is immediately and directly passed to
target.write() for writing to the file.

> Walter, thanks a lot for taking your time to help me out.

You're welcome, hope it helps.

Walter

From fpb01 at health.state.ny.us  Thu Jan 12 22:20:12 2012
From: fpb01 at health.state.ny.us (Francis P. Boscoe)
Date: Thu, 12 Jan 2012 16:20:12 -0500
Subject: [Tutor] read in text file containing non-English characters
Message-ID: <OFB973805A.06EBB8F9-ON85257983.007338C6-85257983.007538DF@notes.health.state.ny.us>



Given a simple text file of departments, capitals, longitude and latitude
separated by commas

Ahuachap?n,Ahuachap?n,-89.8450,13.9190
Caba?as,Sensuntepeque,-88.6300,13.8800
Cuscatl?n,Cojutepeque,-88.9333,13.7167

I would like to know to how to read in the file and then access arbitary
rows in the file, so that I can print a line such as:

The capital of Caba?as is Sensuntepeque

while preserving the non-English characters

now, for example, I get

Caba??as

Thanks.







IMPORTANT NOTICE: This e-mail and any attachments may contain confidential or sensitive information which is, or may be, legally privileged or otherwise protected by law from further disclosure. It is intended only for the addressee. If you received this in error or from someone who was not authorized to send it to you, please do not distribute, copy or use it or any attachments. Please notify the sender immediately by reply e-mail and delete this from your system. Thank you for your cooperation. 

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

From cmathe7 at gmail.com  Thu Jan 12 23:48:56 2012
From: cmathe7 at gmail.com (Claude Matherne)
Date: Thu, 12 Jan 2012 17:48:56 -0500
Subject: [Tutor] Trying to access a random value in a list
Message-ID: <CAApS7HC=xJxqHBDPEY6-GjNmERroSBpTVgbY1OG3DRUh9oLx+A@mail.gmail.com>

Hello all,
I am a beginner to python and I am trying to make a simple program that
takes in some names as input into a list and then randomly picks a vaule
from that list as a winner.

Here is the code:

import random

choice = None

names = [ ]

while choice != "0":
    print(
        """
        0 - Exit
        1 - Enter a name
        2 - Pick a winner
        """)
    choice = input("Choice: ")
    print()

    if choice == "0":
        print ("Goodbye.")

    elif choice == "1":
        name = input("Please enter a name: ")
        names.append(name)
        print (names, "have been entered.")

    elif choice == "2":
        pick = len(names)
        win_number =random.randint(0,pick)
        print (names[win_number], " is the winner!")

input("/n/nPress enter to exit.")


First problem, sometimes I get a error where the value is out of range.
Problem becuase of the way I set up the random value.
Second problem, but not a big one, is when I print the lists of names as
they are entered, I get quotations around the name.

I'm sur I am over thinking this, but any help would be great.

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120112/039b50f5/attachment.html>

From ramit.prasad at jpmorgan.com  Fri Jan 13 00:16:31 2012
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Thu, 12 Jan 2012 23:16:31 +0000
Subject: [Tutor] read in text file containing non-English characters
In-Reply-To: <OFB973805A.06EBB8F9-ON85257983.007338C6-85257983.007538DF@notes.health.state.ny.us>
References: <OFB973805A.06EBB8F9-ON85257983.007338C6-85257983.007538DF@notes.health.state.ny.us>
Message-ID: <5B80DD153D7D744689F57F4FB69AF4740C35BF@SCACMX008.exchad.jpmchase.net>

>I would like to know to how to read in the file and then access arbitary rows in the file, so that I can print a line such as: 
> Caba?as,Sensuntepeque,-88.6300,13.8800
>The capital of Caba?as is Sensuntepeque

>while preserving the non-English characters

>now, for example, I get

>Caba??as

Make sure to open the file with correct encoding or convert in your program. 
Incorrect encoding is a very likely reason why you get funky characters (or
not having the appropriate codepages/languages installed). According to 
the internet you can open the file and specify the encoding all at once.
http://docs.python.org/library/codecs.html#codecs.open 
>>>import codecs
>>>f = codecs.open("test", "r", "utf-8")

The list of standard codecs is on that page at 7.8.3.

You can also manually convert a string, but that is more of a pain..and you 
would still need to know the codec.

As for the rest of the problem, I would suggest you take a quick peek at the csv
module which will parse your data for you. 

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--
 
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From pacificmorrowind at gmail.com  Fri Jan 13 00:56:32 2012
From: pacificmorrowind at gmail.com (Nick W)
Date: Thu, 12 Jan 2012 15:56:32 -0800
Subject: [Tutor] Trying to access a random value in a list
In-Reply-To: <CAApS7HC=xJxqHBDPEY6-GjNmERroSBpTVgbY1OG3DRUh9oLx+A@mail.gmail.com>
References: <CAApS7HC=xJxqHBDPEY6-GjNmERroSBpTVgbY1OG3DRUh9oLx+A@mail.gmail.com>
Message-ID: <CAHXRGSOEYdAuQQfkwparewGfKWtmtH_ODpQ1gr8CAuhBhE0eLA@mail.gmail.com>

first problem: easy fix just remember that len() returns the actual
number of items in the list but that list is indexed starting at 0 so
just replace your line of
        pick = len(names)
with:
       pick = len(names) - 1
and for problem #2:
just use string formating... like for example instead of:
        print (names[win_number], " is the winner!")
try something along the lines of:
       print("{} is a winner".format(names[win_number]))
HTH
Pacific Morrowind

On 1/12/12, Claude Matherne <cmathe7 at gmail.com> wrote:
> Hello all,
> I am a beginner to python and I am trying to make a simple program that
> takes in some names as input into a list and then randomly picks a vaule
> from that list as a winner.
>
> Here is the code:
>
> import random
>
> choice = None
>
> names = [ ]
>
> while choice != "0":
>     print(
>         """
>         0 - Exit
>         1 - Enter a name
>         2 - Pick a winner
>         """)
>     choice = input("Choice: ")
>     print()
>
>     if choice == "0":
>         print ("Goodbye.")
>
>     elif choice == "1":
>         name = input("Please enter a name: ")
>         names.append(name)
>         print (names, "have been entered.")
>
>     elif choice == "2":
>         pick = len(names)
>         win_number =random.randint(0,pick)
>         print (names[win_number], " is the winner!")
>
> input("/n/nPress enter to exit.")
>
>
> First problem, sometimes I get a error where the value is out of range.
> Problem becuase of the way I set up the random value.
> Second problem, but not a big one, is when I print the lists of names as
> they are entered, I get quotations around the name.
>
> I'm sur I am over thinking this, but any help would be great.
>
> Thanks
>

From bgailer at gmail.com  Fri Jan 13 01:04:17 2012
From: bgailer at gmail.com (bob gailer)
Date: Thu, 12 Jan 2012 19:04:17 -0500
Subject: [Tutor] Trying to access a random value in a list
In-Reply-To: <CAApS7HC=xJxqHBDPEY6-GjNmERroSBpTVgbY1OG3DRUh9oLx+A@mail.gmail.com>
References: <CAApS7HC=xJxqHBDPEY6-GjNmERroSBpTVgbY1OG3DRUh9oLx+A@mail.gmail.com>
Message-ID: <4F0F7501.4000403@gmail.com>

On 1/12/2012 5:48 PM, Claude Matherne wrote:
> Hello all,
> I am a beginner to python and I am trying to make a simple program 
> that takes in some names as input into a list and then randomly picks 
> a vaule from that list as a winner.
> Here is the code:
> import random
> choice = None
> names = [ ]
> while choice != "0":
>     print(
>         """
>         0 - Exit
>         1 - Enter a name
>         2 - Pick a winner
>         """)
>     choice = input("Choice: ")
>     print()
>     if choice == "0":
>         print ("Goodbye.")
>     elif choice == "1":
>         name = input("Please enter a name: ")
>         names.append(name)
>         print (names, "have been entered.")
>     elif choice == "2":
>         pick = len(names)
>         win_number =random.randint(0,pick)
>         print (names[win_number], " is the winner!")
> input("/n/nPress enter to exit.")
> First problem, sometimes I get a error where the value is out of 
> range.  Problem becuase of the way I set up the random value.
randint returns random integer in range [a, b], including both end 
points. List indexes start at 0. Sufficient?

> Second problem, but not a big one, is when I print the lists of names 
> as they are entered, I get quotations around the name.
I bet you are seeing something like ['joe', pete'] since you are 
printing a list. true? In general copy and paste the undesired output in 
the email. Try print(','.join(names)

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


From d at davea.name  Fri Jan 13 01:07:55 2012
From: d at davea.name (Dave Angel)
Date: Thu, 12 Jan 2012 19:07:55 -0500
Subject: [Tutor] Trying to access a random value in a list
In-Reply-To: <CAHXRGSOEYdAuQQfkwparewGfKWtmtH_ODpQ1gr8CAuhBhE0eLA@mail.gmail.com>
References: <CAApS7HC=xJxqHBDPEY6-GjNmERroSBpTVgbY1OG3DRUh9oLx+A@mail.gmail.com>
	<CAHXRGSOEYdAuQQfkwparewGfKWtmtH_ODpQ1gr8CAuhBhE0eLA@mail.gmail.com>
Message-ID: <4F0F75DB.6090307@davea.name>

On 01/12/2012 06:56 PM, Nick W wrote:
> first problem: easy fix just remember that len() returns the actual
> number of items in the list but that list is indexed starting at 0 so
> just replace your line of
>          pick = len(names)
> with:
>         pick = len(names) - 1
> and for problem #2:
> just use string formating... like for example instead of:
>          print (names[win_number], " is the winner!")
> try something along the lines of:
>         print("{} is a winner".format(names[win_number]))
> HTH
> Pacific Morrowind
>
You top-posted.  On lists like this one, it's proper to add your new 
message after the piece you're quoting.

> On 1/12/12, Claude Matherne<cmathe7 at gmail.com>  wrote:
>> Hello all,
>> I am a beginner to python and I am trying to make a simple program that
>> takes in some names as input into a list and then randomly picks a vaule
>> from that list as a winner.
>>
>> Here is the code:
>>
>> import random
>>
>> choice = None
>>
>> names = [ ]
>>
>> while choice != "0":
>>      print(
>>          """
>>          0 - Exit
>>          1 - Enter a name
>>          2 - Pick a winner
>>          """)
>>      choice = input("Choice: ")
>>      print()
>>
>>      if choice == "0":
>>          print ("Goodbye.")
>>
>>      elif choice == "1":
>>          name = input("Please enter a name: ")
>>          names.append(name)
>>          print (names, "have been entered.")
>>
>>      elif choice == "2":
>>          pick = len(names)
>>          win_number =random.randint(0,pick)
>>          print (names[win_number], " is the winner!")
>>
>> input("/n/nPress enter to exit.")
>>
>>
>> First problem, sometimes I get a error where the value is out of range.
>> Problem becuase of the way I set up the random value.
>> Second problem, but not a big one, is when I print the lists of names as
>> they are entered, I get quotations around the name.
>>
>> I'm sur I am over thinking this, but any help would be great.
>>
>> Thanks
>>
The problem with the quotes is just the way that Python works.
            print (names, "have been entered.")

You're printing a list as a whole, and when it does that, individual 
items are displayed using repr(), rather than str().  If you don't like 
that, write a loop, with a print statement per item, and format it any 
way you like.

           for name in names:
                   print(name, "+whatever")

-- 

DaveA


From marc.tompkins at gmail.com  Fri Jan 13 01:49:06 2012
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 12 Jan 2012 16:49:06 -0800
Subject: [Tutor] read in text file containing non-English characters
In-Reply-To: <OFB973805A.06EBB8F9-ON85257983.007338C6-85257983.007538DF@notes.health.state.ny.us>
References: <OFB973805A.06EBB8F9-ON85257983.007338C6-85257983.007538DF@notes.health.state.ny.us>
Message-ID: <CAKK8jXbdeQGNjz3xs+JT5HZ6MhVzhMPuUCUxUp-JzA-wSAYDUw@mail.gmail.com>

On Thu, Jan 12, 2012 at 1:20 PM, Francis P. Boscoe <fpb01 at health.state.ny.us
> wrote:

> Given a simple text file of departments, capitals, longitude and latitude
> separated by commas
>
> Ahuachap?n,Ahuachap?n,-89.8450,13.9190
> Caba?as,Sensuntepeque,-88.6300,13.8800
> Cuscatl?n,Cojutepeque,-88.9333,13.7167
>
> I would like to know to how to read in the file and then access arbitary
> rows in the file, so that I can print a line such as:
>
> The capital of Caba?as is Sensuntepeque
>
> while preserving the non-English characters
>
> now, for example, I get
>
> Caba??as
>
>
I'm going to go out on a limb here and guess that you're not yet
comfortable with Unicode. It's all right - we've all been there, and
sometimes I still wake up in a cold sweat thinking about it - but you owe
it to yourself to get at least a bit more comfortable with encodings,
character sets, etc.
Joel Spolsky - Joel on Software - wrote a pretty good intro a few years
ago.  It's geared toward HTML, but the concepts are the same regardless of
language.  It's a fun read, and informative - I recommend
it.<http://www.theregister.co.uk/2012/01/12/oracle_netra_t4_timesten/>
www.joelonsoftware.com/articles/Unicode.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120112/a55e6756/attachment.html>

From martin at linux-ip.net  Fri Jan 13 04:18:34 2012
From: martin at linux-ip.net (Martin A. Brown)
Date: Thu, 12 Jan 2012 22:18:34 -0500
Subject: [Tutor] read in text file containing non-English characters
In-Reply-To: <OFB973805A.06EBB8F9-ON85257983.007338C6-85257983.007538DF@notes.health.state.ny.us>
References: <OFB973805A.06EBB8F9-ON85257983.007338C6-85257983.007538DF@notes.health.state.ny.us>
Message-ID: <alpine.LNX.2.00.1201122137490.5877@paprika.renesys.com>


Greetings Francis,

You have entered the Unicode or multiple character set zone.  This 
is the deep end of the pool, and even experienced practitioners have 
difficulty here.  Fortunately, Python eases the burden on you, but 
this still requires some care.

 : Given a simple text file of departments, capitals, longitude and 
 : latitude separated by commas

Side notes--if you are dealing with geographic hierarchies, you may 
wish to consider using some publicly 'standard' available hierarchy.  

Since you are mailing from a .state.ny.us address, I might guess 
that you are working inside a context in which you may not have 
control over the source of the geographic hierachical data, however, 
I'll point out the following:

  * GeoNames:  http://www.geonames.org/
  * GNIS: http://en.wikipedia.org/wiki/Geographic_Names_Information_System

Apologies to somebody with actual brains who said this, but:  The 
great thing about standards, is that you have so many to choose 
from.

OK, so that's unrelated to your direct question.  You have a few 
capitals and latlongs that you want to read from a comma-separated 
file.

 : Ahuachap?n,Ahuachap?n,-89.8450,13.9190
 : Caba?as,Sensuntepeque,-88.6300,13.8800
 : Cuscatl?n,Cojutepeque,-88.9333,13.7167
 : 
 : I would like to know to how to read in the file and then access 
 : arbitary rows in the file, so that I can print a line such as:
 : 
 : The capital of Caba?as is Sensuntepeque
 : 
 : while preserving the non-English characters
 : 
 : now, for example, I get
 : 
 : Caba??as

You don't show even a snippet of code.  If you are asking 
for help here, it is good form to show us your code.  Since 
you don't state how you are reading the data and how you are 
printing the data, we can't help much.  Here are some tips:

  * Consider learning how to use the csv module, particularly in 
    your case, csv.reader (as Ramit Prasad has already suggested).

  * Consider checking the bytestream to see if the bytes produced
    on output are the same as on input (also, read the text that 
    Mark Tompkins indicated and learn to distinguish Unicode from 
    UTF-8).

  * Report back to the list the version of Python you are using.
    [Different versions of Python have subtly different handling of
    non ASCII character set data, but this should probably not be an 
    issue for the more obvious issue you are showing above.]

We can have no idea what your ultimate goal is with the data, but 
can help you much more if you show us the code.

Here's a sample of what I would/could do (Python 2.6.5):

    import csv
    reader = csv.reader(open('input-data.txt'),delimiter=',')
    for row in reader:
        print 'The capital of %s is %s' % (row[0], row[1],)

The above is trivial, but if you would like some more substantive 
assistance, you should describe your problem in a bit more detail.

-Martin

-- 
Martin A. Brown
http://linux-ip.net/

From jakhead at gmail.com  Fri Jan 13 04:44:22 2012
From: jakhead at gmail.com (Chase Franklin)
Date: Thu, 12 Jan 2012 21:44:22 -0600
Subject: [Tutor] Tkinter event handler
Message-ID: <CAEL8JpGceNFMArQpm_E--=-etFmbPSz=a7nwniFiDXzyMDQAPw@mail.gmail.com>

Hello all,
I use emacs' org-mode for note taking in my classes. I have a simple
script that starts emacs and creates a new .org file with an id number
and date like so:
001_Jan_12_2012.org

I'd like to include the class name so that it becomes:
001_Jan_12_2012_CLASSNAME.org

So I have a simple Tk window that is populated by a list of class names.

Ex:
1. Class One
2. Class Two
3. Class Three

Idealy, at this prompt I'd like to simply press the corresponding
number and be on to emacs with the Class Name added to the file name
as above. I know how to hard code this for each keypress, but is there
a way to create the events dynamically so that when the list changes
the keys follow suit? I hope I've been clear enough, thanks!

From alan.gauld at btinternet.com  Fri Jan 13 09:45:20 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 13 Jan 2012 08:45:20 +0000
Subject: [Tutor] Tkinter event handler
In-Reply-To: <CAEL8JpGceNFMArQpm_E--=-etFmbPSz=a7nwniFiDXzyMDQAPw@mail.gmail.com>
References: <CAEL8JpGceNFMArQpm_E--=-etFmbPSz=a7nwniFiDXzyMDQAPw@mail.gmail.com>
Message-ID: <jeoqv1$n94$1@dough.gmane.org>

On 13/01/12 03:44, Chase Franklin wrote:

> I'd like to include the class name so that it becomes:
> 001_Jan_12_2012_CLASSNAME.org
>
> So I have a simple Tk window that is populated by a list of class names.

What is a "Simple Tk window"?
There is no such widget. So what is the window using to list the names?
Is it a label?
a text widget? or a List entry woidget(which would seem the most logical)

> 1. Class One
> 2. Class Two
> 3. Class Three
>
> Idealy, at this prompt I'd like to simply press the corresponding
> number and be on to emacs with the Class Name added to the file name

When you say press the "number" do you mean you want the user to point 
at the digit part of the line?
Why not just have them click on the line itself?
That's what a list entry does by default.

You can then select as much or as little of the seleced text to put in 
your filename.

> as above. I know how to hard code this for each keypress, but is there
> a way to create the events dynamically so that when the list changes
> the keys follow suit? I hope I've been clear enough, thanks!

I don;t undertsamd this at all.
Tk events are all created dynamically but they have nothing to do ewith 
the content of the list.

I think you need to show us some code. At the moment its not at all 
clear(to me) what you are trying to do.

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


From fpb01 at health.state.ny.us  Fri Jan 13 15:52:40 2012
From: fpb01 at health.state.ny.us (Francis P. Boscoe)
Date: Fri, 13 Jan 2012 09:52:40 -0500
Subject: [Tutor] Read in text file containing non-English characters
In-Reply-To: <mailman.25313.1326425009.27777.tutor@python.org>
References: <mailman.25313.1326425009.27777.tutor@python.org>
Message-ID: <OFF44D6F3B.0E72C2B7-ON85257984.004FDEFC-85257984.0051BE18@notes.health.state.ny.us>










>You don't show even a snippet of code.  If you are asking
>for help here, it is good form to show us your code.  Since
>you don't state how you are reading the data and how you are
>printing the data, we can't help much.  Here are some tips:
>
>  * Consider learning how to use the csv module, particularly in
>    your case, csv.reader (as Ramit Prasad has already suggested).
>
>  * Consider checking the bytestream to see if the bytes produced
>    on output are the same as on input (also, read the text that
>    Mark Tompkins indicated and learn to distinguish Unicode from
>    UTF-8).
>
>  * Report back to the list the version of Python you are using.
>    [Different versions of Python have subtly different handling of
>    non ASCII character set data, but this should probably not be an
>    issue for the more obvious issue you are showing above.]
>
>We can have no idea what your ultimate goal is with the data, but
>can help you much more if you show us the code.
>
>Here's a sample of what I would/could do (Python 2.6.5):
>
>    import csv
>    reader = csv.reader(open('input-data.txt'),delimiter=',')
>    for row in reader:
>        print 'The capital of %s is %s' % (row[0], row[1],).
>
>The above is trivial, but if you would like some more substantive
>assistance, you should describe your problem in a bit more detail.


I apologize for not including any code, but that's because I didn't have
any. I had no idea where to even begin. I have a 450 page book on beginner
Python programming and nothing like the above is in there. Incidentally,
when I try the above code in Python 3.2 I get an "invalid syntax" message.

My ultimate goal is to be able to do what I've done for years in SAS, where
I consider myself an expert: read in some raw data, perform some
mathematical operations on the data, then output it.  Later this spring I
will be teaching an audience that does not have access to SAS (community
college students) and Python was suggested as an alternative.

IMPORTANT NOTICE: This e-mail and any attachments may contain confidential or sensitive information which is, or may be, legally privileged or otherwise protected by law from further disclosure. It is intended only for the addressee. If you received this in error or from someone who was not authorized to send it to you, please do not distribute, copy or use it or any attachments. Please notify the sender immediately by reply e-mail and delete this from your system. Thank you for your cooperation. 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120113/f2fc286e/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: graycol.gif
Type: image/gif
Size: 105 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120113/f2fc286e/attachment.gif>

From david at graniteweb.com  Fri Jan 13 15:57:43 2012
From: david at graniteweb.com (David Rock)
Date: Fri, 13 Jan 2012 08:57:43 -0600
Subject: [Tutor] PYTHONPATH (Mac OS X)
In-Reply-To: <CAK5fS_FafMq4bTLuxKt2=rZL3KdQr_qckMSt7QHqey5UJv0YJA@mail.gmail.com>
References: <CAK5fS_GMBAiQNwVo1_qZODZStT5BOuWJV0DEp1-6W5S_3DPczw@mail.gmail.com>
	<4EEEA9D5.70605@gmail.com>
	<CAK5fS_E1aDVr2VAbxS5daB43ew+LP_1nJHL3qYM8_v8_vneOpA@mail.gmail.com>
	<jcpj6l$kfq$1@dough.gmane.org>
	<CAK5fS_GU7P=ZuR=05CCgJipoq4kG7dg2ivJPPChSP1ern9Zx3w@mail.gmail.com>
	<jd8aom$enq$1@dough.gmane.org>
	<CAK5fS_FEAVTBwBKoLkTKW8cDJA_iqV-Co9PX9Y=L-MH_Ep+vRQ@mail.gmail.com>
	<jda9ti$g1m$1@dough.gmane.org>
	<CAK5fS_FafMq4bTLuxKt2=rZL3KdQr_qckMSt7QHqey5UJv0YJA@mail.gmail.com>
Message-ID: <20120113145743.GA4366@wdfs.graniteweb.com>

* Stayvoid <stayvoid at gmail.com> [2011-12-30 16:11]:
> >You don't have any option.
> >You either type in the full path or you get the user to tell you
> >in some way - either with a prompt or via an input argument.
> 
> OK, now I get it.
> 
> How can I tell this to the end-user?
> Should I write a README file or what?
> 
> I've tried to run lengthcounter_lutz from the file's folder and this worked out.
> cd /Users/Username/Python_modules/
> python /Users/Username/Python_modules/lengthcounter_lutz.py
> ('Lines:', 12, 'Chars:', 285)
> 
> 
> But I can't understand what's wrong with the second one:
> def countLines(name):
>     file = open(name.__file__)
>     return len(file.readlines())
> 
> def countChars(name):
>     return len(open(name.__file__).read())
> 
> def test(name):
>     return "Lines:", countLines(name), "Chars:", countChars(name)
> 
> if __name__ == '__main__':
>     import lengthcounter
>     print test(lengthcounter)
> 
> >>> import lengthcounter
> >>> lengthcounter.test(lengthcounter)
> ('Lines:', 5, 'Chars:', 885)
> 

Looking at page 1119 in the learning Python book, I might venture a
guess as to where the difference lies.  You are calling test as:
test(lengthcounter), but that is not the name of a file (the name of a
file should be in quotes). lengthcounter in this case is a variable, 
not a filename.  The behavior in this case is probably undetermined.

I suggest doing a manual check on the file named lengthcounter.pyc, and
I'll bet you will find something closer to 5 lines and 885 characters.
pyc files are the bytecode version of your file that gets generated
automatically and is the code that is actually executed.

Somehow, calling the method test inside the interpreter is different
from running it on the commandline and you are picking up the pyc file.  
In either case, this format is iffy at best:

if __name__ == '__main__':
    import lengthcounter
    print test(lengthcounter)

should really be:

if __name__ == '__main__':
    import lengthcounter
    print lengthcounter.test(lengthcounter)

to avoid ambiguous behavior.

-- 
David Rock
david at graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 190 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120113/aed72e4e/attachment.pgp>

From 0101amt at gmail.com  Fri Jan 13 16:38:45 2012
From: 0101amt at gmail.com (amt)
Date: Fri, 13 Jan 2012 17:38:45 +0200
Subject: [Tutor] Are there other ways of solving this exercise?
In-Reply-To: <CANLXbfBzZUBX72RBzxGHZXNCgbdfefkX9fKb+ifCPwgkkO6DrQ@mail.gmail.com>
References: <CAEQEn02=VpVxKXRJvzPMpd=+J8mv3cQs4o0Ep20g_08Ov5p5tQ@mail.gmail.com>
	<CANLXbfCpUyDvsP92TiT-NvRMaBL=EF5avAEMgbSkZZ6SPAi4jg@mail.gmail.com>
	<CAEQEn034PQ08EGQmXjCRA_841YSXxXHOU0_iwLfbeHSVc=xf3g@mail.gmail.com>
	<CANLXbfAHcdwpkmDzoknh4CzYJn1y1MDURe8QRmVpBPSYhUaQQw@mail.gmail.com>
	<CAEQEn03Yr9o3a+vW4W+aFU4NhXiTHN=A++F-4gpzhfPOX4X-4A@mail.gmail.com>
	<CANLXbfBzZUBX72RBzxGHZXNCgbdfefkX9fKb+ifCPwgkkO6DrQ@mail.gmail.com>
Message-ID: <CAEQEn03===g3Hcx9Sf5TMAZ7JwJG_9CVP0q9+SwNTagsRGvs1A@mail.gmail.com>

Wow!!! Thanks so much for your reply. It was so nicely written and I
understood everything you said.





Thanks again, have a nice weekend.



Regards,
Amt.

From martin at linux-ip.net  Fri Jan 13 17:59:17 2012
From: martin at linux-ip.net (Martin A. Brown)
Date: Fri, 13 Jan 2012 11:59:17 -0500
Subject: [Tutor] Read in text file containing non-English characters
In-Reply-To: <OFF44D6F3B.0E72C2B7-ON85257984.004FDEFC-85257984.0051BE18@notes.health.state.ny.us>
References: <mailman.25313.1326425009.27777.tutor@python.org>
	<OFF44D6F3B.0E72C2B7-ON85257984.004FDEFC-85257984.0051BE18@notes.health.state.ny.us>
Message-ID: <alpine.LNX.2.00.1201131102520.5877@paprika.renesys.com>


Greetings Francis,

 : >You don't show even a snippet of code.  If you are asking
 : >for help here, it is good form to show us your code.  Since
 : >you don't state how you are reading the data and how you are
 : >printing the data, we can't help much.  Here are some tips:
 : >
 : >  * Consider learning how to use the csv module, particularly in
 : >    your case, csv.reader (as Ramit Prasad has already suggested).
 : >
 : >  * Consider checking the bytestream to see if the bytes produced
 : >    on output are the same as on input (also, read the text that
 : >    Mark Tompkins indicated and learn to distinguish Unicode from
 : >    UTF-8).
 : >
 : >  * Report back to the list the version of Python you are using.
 : >    [Different versions of Python have subtly different handling of
 : >    non ASCII character set data, but this should probably not be an
 : >    issue for the more obvious issue you are showing above.]
 : >
 : >We can have no idea what your ultimate goal is with the data, but
 : >can help you much more if you show us the code.
 : >
 : >Here's a sample of what I would/could do (Python 2.6.5):
 : >
 : >    import csv
 : >    reader = csv.reader(open('input-data.txt'),delimiter=',')
 : >    for row in reader:
 : >        print 'The capital of %s is %s' % (row[0], row[1],).
 : >
 : >The above is trivial, but if you would like some more substantive
 : >assistance, you should describe your problem in a bit more detail.
 : 
 : 
 : I apologize for not including any code, but that's because I 
 : didn't have any. I had no idea where to even begin. I have a 450 
 : page book on beginner Python programming and nothing like the 
 : above is in there. Incidentally, when I try the above code in 
 : Python 3.2 I get an "invalid syntax" message.

One of the famous differences between Python 2.x and Python 3.x [0] 
is 'print'.  Try this:

    import csv
    reader = csv.reader(open('input-data.txt'),delimiter=',')
    for row in reader:
        print('The capital of %s is %s' % (row[0], row[1],))

 : My ultimate goal is to be able to do what I've done for years in 
 : SAS, where I consider myself an expert: read in some raw data, 
 : perform some mathematical operations on the data, then output it.  
 : Later this spring I will be teaching an audience that does not 
 : have access to SAS (community college students) and Python was 
 : suggested as an alternative.

OK, so this list is a good place to be for such initial 
explorations.  There are a number of libraries that can help with 
the mathematical operations and you will probably get many good 
suggestions.

Welcome to the list,

-Martin

 [0] http://wiki.python.org/moin/Python2orPython3

--
Martin A. Brown
http://linux-ip.net/

From jakhead at gmail.com  Fri Jan 13 20:50:41 2012
From: jakhead at gmail.com (CF)
Date: Fri, 13 Jan 2012 13:50:41 -0600
Subject: [Tutor] Tkinter event handler
In-Reply-To: <jeoqv1$n94$1@dough.gmane.org>
References: <CAEL8JpGceNFMArQpm_E--=-etFmbPSz=a7nwniFiDXzyMDQAPw@mail.gmail.com>
	<jeoqv1$n94$1@dough.gmane.org>
Message-ID: <CAEL8JpE1Aq3BS6fF6c21LF5co-9BTHEiPPEYM6Fyw4=Bpg+RkA@mail.gmail.com>

I apologize, I didn't realize how tired I was. I've got it working,
sort of, after finding the event.char attribute. I needed it to work
via keyboard since I don't use a mouse often and I'm running this with
awesome-wm's launcher so it can't get input from the terminal (as far
as I know) and I didn't know another way to have it prompt me for
input except with Tk. Here's what I've got:

def key(event):
    class_list = read_object('.create_note_classes') # pickle file
list of class names
    class_list.sort()

    class_name = class_list[int(event.char) - 1]
    id = new_id() # this gets the appropriate number for filename ex: 001
    today = get_date() # gets date and formats it

    filename = '%03d_%s_%s.org' % (id, today, class_name)
    ## ex: 001_Jan_13_2012_Economics.org
    window.destroy()
    subprocess.call(['emacs', filename])


class_list = read_object('.create_note_classes')
class_list.sort()

window = Tk()
for i, v in enumerate(class_list):
    v = Label(text='%d %s' % (i + 1, v)).pack()

window.bind_all('<key>', key)
window.mainloop()


I'm going to change this to use the listbox widget though since you
mentioned it. It's ugly I know, this is the first thing I've tried
writing with python (2.7 btw).

From wprins at gmail.com  Fri Jan 13 23:30:12 2012
From: wprins at gmail.com (Walter Prins)
Date: Fri, 13 Jan 2012 22:30:12 +0000
Subject: [Tutor] Read in text file containing non-English characters
In-Reply-To: <OFF44D6F3B.0E72C2B7-ON85257984.004FDEFC-85257984.0051BE18@notes.health.state.ny.us>
References: <mailman.25313.1326425009.27777.tutor@python.org>
	<OFF44D6F3B.0E72C2B7-ON85257984.004FDEFC-85257984.0051BE18@notes.health.state.ny.us>
Message-ID: <CANLXbfCV-X0e+utcwSFEw+V2=L4LuCepDZ=2N=QKW7o-=5qHCA@mail.gmail.com>

Hi Francis,

On 13 January 2012 14:52, Francis P. Boscoe <fpb01 at health.state.ny.us> wrote:
>> I apologize for not including any code, but that's because I didn't have any. I had no idea where to even begin. I have a 450 page book on beginner Python programming and nothing like the above is in >there. Incidentally, when I try the above code in Python 3.2 I get an "invalid syntax" message.

As mentioned by Martin, the reason you get a syntax error is because
the print statement doesn't exist anymore in Python 3.x -- ?It's been
replaced with a print() function to make it more consistent with the
rest of the language.

That said, please be aware that there's many changes between Python
2.x and 3.x, even though they look and act more similar than not.
Nevertheless you should be aware of which major version you're using
and make adjustments accordingly. ?As of right now, unless you have
particular reason to do so, I'd say stick with Python 2.7 and only
switch to Python 3.2 or better once you have a handle on the basics on
unless you have a specific reason to go with 3.x. However, one of the
big differences as mention before between Python 2.x and 3.x is
Unicode handling so this might be one reason for you to actually have
a more serious look at Python 3.x despite what I've just suggested...

Also, for reference, the following presentation which discusses
differences between Python 2 and Python 3 from an I/O p.o.v. but also
comments quite a bit on the Unicode changes (Unicode has a direct
impact on text I/O) and related subtleties that might bight one if
you're not careful:
http://www.slideshare.net/dabeaz/mastering-python-3-io-version-2

HTH,

Walter

From steve at pearwood.info  Sat Jan 14 01:33:09 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 14 Jan 2012 11:33:09 +1100
Subject: [Tutor] read in text file containing non-English characters
In-Reply-To: <OFB973805A.06EBB8F9-ON85257983.007338C6-85257983.007538DF@notes.health.state.ny.us>
References: <OFB973805A.06EBB8F9-ON85257983.007338C6-85257983.007538DF@notes.health.state.ny.us>
Message-ID: <4F10CD45.7050401@pearwood.info>

On 13/01/12 08:20, Francis P. Boscoe wrote:
>
>
> Given a simple text file of departments, capitals, longitude and latitude
> separated by commas
>
> Ahuachap?n,Ahuachap?n,-89.8450,13.9190
> Caba?as,Sensuntepeque,-88.6300,13.8800
> Cuscatl?n,Cojutepeque,-88.9333,13.7167
>
> I would like to know to how to read in the file and then access arbitary
> rows in the file, so that I can print a line such as:
>
> The capital of Caba?as is Sensuntepeque
>
> while preserving the non-English characters

What version of Python are you using? This is likely to be easier in Python 
3.1 or 3.2; if you can upgrade to either of those, that will make your life 
easier in the long run.

First off, you need to know what encoding the source file is. You call it a 
"simple text file", but there is no such thing once you include non-ASCII 
values! The truth is, there never was such a thing, but so long as people only 
included ASCII characters in files, we could ignore the complexity.

If you don't understand what I mean by "encoding", I strongly recommend you 
read Joel On Software:

http://www.joelonsoftware.com/articles/Unicode.html

If you don't know what the encoding is, you have to guess, or give up. 
Possibly ask the supplier of the file. There are software libraries which will 
read a text file and try to guess the encoding for you. Or when in doubt, just 
try UTF-8.

I have created a text file containing the three lines above, starting with 
Ahuachap?n. Because I have created it, I know that the encoding I used was 
UTF-8. (If you are creating your own data files, *always* use UTF-8 unless you 
have a specific reason why you shouldn't.) But I'm going to pretend that I 
don't know this, and show you what happens when I get the encoding wrong.

This is using Python 2.6.


py> import codecs
py> for line in codecs.open('test.txt', encoding='latin1'):
...     print line.strip()  # strip() removes the trailing newline
...
Ahuachap??n,Ahuachap??n,-89.8450,13.9190
Caba??as,Sensuntepeque,-88.6300,13.8800
Cuscatl??n,Cojutepeque,-88.9333,13.7167


So I got the encoding wrong. The incorrect characters like ?? are often known 
by the Japanese term "moji-bake", and that's a good sign of encoding problems. 
Here's another wrong guess:


py> for line in codecs.open('test.txt', encoding='ascii'):
...     print line.strip()
...
Traceback (most recent call last):
   [ ... traceback deleted for brevity ... ]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 8: 
ordinal not in range(128)

So when you get the encoding wrong, two things may happen: you get an error, 
telling you you got it wrong, or you get junk output, which if you are really 
unlucky might look like legitimate output.

This is what happens when I use the correct encoding:

py> for line in codecs.open('test.txt', encoding='utf8'):
...     print line.strip()
...
Ahuachap?n,Ahuachap?n,-89.8450,13.9190
Caba?as,Sensuntepeque,-88.6300,13.8800
Cuscatl?n,Cojutepeque,-88.9333,13.7167


It just works perfectly.

Now, this is how to actually do some useful work with the data. Assuming you 
are using at least version 2.6 (possibly even 2.5, but definitely not 2.4) 
this should work nicely:


py> from collections import namedtuple
py> Record = namedtuple('Record', 'capital region x y')
py> data = []
py> for line in codecs.open('test.txt', encoding='utf8'):
...     line = line.strip()
...     data.append(Record(*line.split(',')))
...
py> for record in data:
...     print "The capital of", record.region, "is", record.capital
...
The capital of Ahuachap?n is Ahuachap?n
The capital of Sensuntepeque is Caba?as
The capital of Cojutepeque is Cuscatl?n



Hope this helps and gets you started.



Regards,


-- 
Steven

From steve at pearwood.info  Sat Jan 14 04:18:09 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 14 Jan 2012 14:18:09 +1100
Subject: [Tutor] Trying to access a random value in a list
In-Reply-To: <CAHXRGSOEYdAuQQfkwparewGfKWtmtH_ODpQ1gr8CAuhBhE0eLA@mail.gmail.com>
References: <CAApS7HC=xJxqHBDPEY6-GjNmERroSBpTVgbY1OG3DRUh9oLx+A@mail.gmail.com>
	<CAHXRGSOEYdAuQQfkwparewGfKWtmtH_ODpQ1gr8CAuhBhE0eLA@mail.gmail.com>
Message-ID: <4F10F3F1.4010508@pearwood.info>

On 13/01/12 10:56, Nick W wrote:
> first problem: easy fix just remember that len() returns the actual
> number of items in the list but that list is indexed starting at 0 so
> just replace your line of
>          pick = len(names)
> with:
>         pick = len(names) - 1


Another good trick for choosing a random value from a list is to avoid picking 
a number first and just ask for a random choice:


 >>> import random
 >>> L = ['spam', 'ham', 'cheese', 'eggs']
 >>> random.choice(L)
'cheese'



> and for problem #2:
> just use string formating... like for example instead of:
>          print (names[win_number], " is the winner!")
> try something along the lines of:
>         print("{} is a winner".format(names[win_number]))

Apart from being longer and harder, is there an advantage to the second form?

:)

A third alternative is:

print("%s is a winner" % names[win_number])

In any case, none of these solve the actual problem. The original poster is 
talking about printing the list of names:

print (names, "have been entered.")

which prints an actual LIST, so you get (e.g.):

['fred', 'barney']

instead of:

fred barney

The easy way to fix that is to use:

print (" ".join(names), "have been entered.")



-- 
Steven

From ckava1 at msn.com  Sun Jan 15 03:55:06 2012
From: ckava1 at msn.com (Chris Kavanagh)
Date: Sat, 14 Jan 2012 21:55:06 -0500
Subject: [Tutor] Simple Question (I Hope)
Message-ID: <BLU0-SMTP371470DFD22FECC5378A4CC8A820@phx.gbl>

I was looking at this code from the Python Docs 
(http://docs.python.org/library/email-examples.html), trying to learn 
how to send email from a Pyhton script. Anyways, part of this code 
confused me. Here's the script:

1 # Import smtplib for the actual sending function
2 import smtplib
3
4 # Import the email modules we'll need
5 from email.mime.text import MIMEText
6
7 # Open a plain text file for reading.  For this example, assume that
8 # the text file contains only ASCII characters.
9 fp = open(textfile, 'rb')
10 # Create a text/plain message
11 msg = MIMEText(fp.read())
12 fp.close()
13
14 # me == the sender's email address
15 # you == the recipient's email address
16 msg['Subject'] = 'The contents of %s' % textfile
17 msg['From'] = me
18 msg['To'] = you
19
20 # Send the message via our own SMTP server, but don't include the
21 # envelope header.
22 s = smtplib.SMTP('localhost')
23 s.sendmail(me, [you], msg.as_string())
24 s.quit()

What I don't understand is lines 16-18, more specifically the 
msg['Subject'] format. I thought this was only done with dics?? 
Obviously the variable msg isn't a dic, so how can this be done??

I actually put lines 11, 16,17,18, in the interpreter, then printed out 
msg, so I get what it's doing, but my question still stands. How can one 
do this, when I thought it could only be done with dictionaries???

Thanks for any help! BTW, using Python27, WinXP.

From mehgcap at gmail.com  Sun Jan 15 04:04:12 2012
From: mehgcap at gmail.com (Alex Hall)
Date: Sat, 14 Jan 2012 22:04:12 -0500
Subject: [Tutor] Simple Question (I Hope)
In-Reply-To: <BLU0-SMTP371470DFD22FECC5378A4CC8A820@phx.gbl>
References: <BLU0-SMTP371470DFD22FECC5378A4CC8A820@phx.gbl>
Message-ID: <CAF=P20XJVs7DdfvOWEbrwo=sWyH4_R05=H0d2C_D87cqqkLsBA@mail.gmail.com>

On 1/14/12, Chris Kavanagh <ckava1 at msn.com> wrote:
> I was looking at this code from the Python Docs
> (http://docs.python.org/library/email-examples.html), trying to learn
> how to send email from a Pyhton script. Anyways, part of this code
> confused me. Here's the script:
>
> 1 # Import smtplib for the actual sending function
> 2 import smtplib
> 3
> 4 # Import the email modules we'll need
> 5 from email.mime.text import MIMEText
> 6
> 7 # Open a plain text file for reading.  For this example, assume that
> 8 # the text file contains only ASCII characters.
> 9 fp = open(textfile, 'rb')
> 10 # Create a text/plain message
> 11 msg = MIMEText(fp.read())
> 12 fp.close()
> 13
> 14 # me == the sender's email address
> 15 # you == the recipient's email address
> 16 msg['Subject'] = 'The contents of %s' % textfile
> 17 msg['From'] = me
> 18 msg['To'] = you
> 19
> 20 # Send the message via our own SMTP server, but don't include the
> 21 # envelope header.
> 22 s = smtplib.SMTP('localhost')
> 23 s.sendmail(me, [you], msg.as_string())
> 24 s.quit()
>
> What I don't understand is lines 16-18, more specifically the
> msg['Subject'] format. I thought this was only done with dics??
> Obviously the variable msg isn't a dic, so how can this be done??
>
> I actually put lines 11, 16,17,18, in the interpreter, then printed out
> msg, so I get what it's doing, but my question still stands. How can one
> do this, when I thought it could only be done with dictionaries???
Just from looking, I can pretty much guarantee that MIMEText, when you
create an instance of it by giving it that file pointer (in other
words, you give it a text file), returns a dictionary automatically. I
have not looked up the module, but just reading that code, I don't
think I have to. Clearly, msg is a dictionary-like object, and since
msg is what the constructor of MIMEText() returns when passed the
content of a file, the constructor must return a dictionary-like
object.
>
> Thanks for any help! BTW, using Python27, WinXP.
> _______________________________________________
> 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 steve at pearwood.info  Sun Jan 15 04:44:17 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 15 Jan 2012 14:44:17 +1100
Subject: [Tutor] Simple Question (I Hope)
In-Reply-To: <BLU0-SMTP371470DFD22FECC5378A4CC8A820@phx.gbl>
References: <BLU0-SMTP371470DFD22FECC5378A4CC8A820@phx.gbl>
Message-ID: <4F124B91.7060608@pearwood.info>

Chris Kavanagh wrote:

> 16 msg['Subject'] = 'The contents of %s' % textfile
> 17 msg['From'] = me
> 18 msg['To'] = you

> What I don't understand is lines 16-18, more specifically the 
> msg['Subject'] format. I thought this was only done with dics?? 
> Obviously the variable msg isn't a dic, so how can this be done??

It works with anything that behaves like a mapping. That includes dicts, 
naturally, but also collections.OrderedDict and any other type of object that 
supports the special __getitem__ method. This includes MIMEText objects, which 
are designed to act like mappings when you set email headers:


py> from email.mime.text import MIMEText
py> msg = MIMEText('This is the body of your email')
py> print(msg)
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

This is the body of your email
py>
py>
py> msg['X-Header'] = 'Nobody expects the Spanish Inquisition!'
py> print(msg)
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
X-Header: Nobody expects the Spanish Inquisition!

This is the body of your email
py>
py>


-- 
Steven


From modulok at gmail.com  Sun Jan 15 05:17:15 2012
From: modulok at gmail.com (Modulok)
Date: Sat, 14 Jan 2012 21:17:15 -0700
Subject: [Tutor] Simple Question (I Hope)
In-Reply-To: <BLU0-SMTP371470DFD22FECC5378A4CC8A820@phx.gbl>
References: <BLU0-SMTP371470DFD22FECC5378A4CC8A820@phx.gbl>
Message-ID: <CAN2+EpYhGoDA0-mv=-CmRj=99eMEwYHWj_DUT4HM94vq5ZY+iw@mail.gmail.com>

On 1/14/12, Chris Kavanagh <ckava1 at msn.com> wrote:
> I was looking at this code from the Python Docs
> (http://docs.python.org/library/email-examples.html), trying to learn
> how to send email from a Pyhton script. Anyways, part of this code
> confused me. Here's the script:
>
> 1 # Import smtplib for the actual sending function
> 2 import smtplib
> 3
> 4 # Import the email modules we'll need
> 5 from email.mime.text import MIMEText
> 6
> 7 # Open a plain text file for reading.  For this example, assume that
> 8 # the text file contains only ASCII characters.
> 9 fp = open(textfile, 'rb')
> 10 # Create a text/plain message
> 11 msg = MIMEText(fp.read())
> 12 fp.close()
> 13
> 14 # me == the sender's email address
> 15 # you == the recipient's email address
> 16 msg['Subject'] = 'The contents of %s' % textfile
> 17 msg['From'] = me
> 18 msg['To'] = you
> 19
> 20 # Send the message via our own SMTP server, but don't include the
> 21 # envelope header.
> 22 s = smtplib.SMTP('localhost')
> 23 s.sendmail(me, [you], msg.as_string())
> 24 s.quit()
>
> What I don't understand is lines 16-18, more specifically the
> msg['Subject'] format. I thought this was only done with dics??
> Obviously the variable msg isn't a dic, so how can this be done??
>
> I actually put lines 11, 16,17,18, in the interpreter, then printed out
> msg, so I get what it's doing, but my question still stands. How can one
> do this, when I thought it could only be done with dictionaries???

Chris,

I haven't looked at the module, but you should be aware that you can have
user-defined classes which behave like builtin types, with their own customised
features. You can also subclass a dict and customise it to do whatever. That
said, as long as an object provides dictionary access methods, it can be
treated like a dict in every respect. As far as python is concerned, if it
looks like a duck and quacks like a duck - it's a duck. (Or in this case a
dict.) It doesn't matter what the 'type' is, what is important is how you can
access it.

Here's an example::


# example.py
# The following exapmle could be done more cleanly by subclassing the builtin
# dict type, but for illustrative purposes this was not done. Instead, we show
# several dict methods being defined on our dict-like class 'Foo':

class Foo(object):
    '''This object behaves like a builtin dict that refuses the value "red".'''
    def __init__(self, x, y):
        self.x = x  #<-- We can have our own properties too.
        self.y = y
        self.data = {}

    def __getitem__(self, key):
        '''Return 'key' when accessed like self[key]'''
        return self.data[key]

    def __setitem__(self, key, value):
        '''Sets self[key] =  value'''
        if value == "red":
            raise ValueError("Red is not acceptable!")
        else:
            self.data[key] = value

    def items(self):
        '''These could do whatever you want.'''
        return self.data.items()

    def keys(self):
        '''These could do whatever you want.'''
        return self.data.keys()

    def values(self):
        '''These could do whatever you want.'''
        return self.data.values()


#===================================================
# Now let's use it!
#===================================================

a = Foo(x=3, y=5)

# Is 'a' a dict?
# False
print type(a)

# Is it an instance of a dict?
# False
print isinstance(a, dict)

# Can we *use* a like a dict?
a['sky'] =  "orange"
a['ocean'] = "blue"

for k,v in a.items():
    print k,v

for v in a.values():
    print v

## Yes! Yet, it has it's own set of unique features:

print a.x           #<-- Prints 3
print a.y           #<-- Prints 5
a['blood'] = "red"  #<-- Raises exception.

From lina.lastname at gmail.com  Sun Jan 15 14:28:18 2012
From: lina.lastname at gmail.com (lina)
Date: Sun, 15 Jan 2012 21:28:18 +0800
Subject: [Tutor] Trying to access a random value in a list
In-Reply-To: <CAApS7HC=xJxqHBDPEY6-GjNmERroSBpTVgbY1OG3DRUh9oLx+A@mail.gmail.com>
References: <CAApS7HC=xJxqHBDPEY6-GjNmERroSBpTVgbY1OG3DRUh9oLx+A@mail.gmail.com>
Message-ID: <CAG9cJmnebOBf3-9iH6M1jMP=1awd5cYhc8E9uBg14H0o9fFSQQ@mail.gmail.com>

On Fri, Jan 13, 2012 at 6:48 AM, Claude Matherne <cmathe7 at gmail.com> wrote:
> Hello all,
> I am a beginner to python and I am trying to make a simple program that
> takes in some names as input into a list?and then randomly picks a vaule
> from that list as a winner.
>
> Here is the code:
>
> import random
>
> choice = None
>
> names = [ ]
>
> while choice != "0":
> ??? print(
> ??????? """
> ??????? 0 - Exit
> ??????? 1 - Enter a name
> ??????? 2 - Pick a winner
> ??????? """)
> ??? choice = input("Choice: ")
> ??? print()
>
> ??? if choice == "0":
> ??????? print ("Goodbye.")

Here better to add
           exit()

>
> ??? elif choice == "1":
> ??????? name = input("Please enter a name: ")
> ??????? names.append(name)
> ??????? print (names, "have been entered.")
>
> ??? elif choice == "2":
> ??????? pick = len(names)
> ??????? win_number =random.randint(0,pick)
> ??????? print (names[win_number], " is the winner!")
>
> input("/n/nPress enter to exit.")
>
>
> First problem, sometimes I get a error where the value is out of range.
> Problem becuase of the way I set up the random value.
> Second problem, but not a big one, is when I print the lists of names as
> they are entered, I get quotations around the name.
>
> I'm sur I am over thinking this, but any help would be great.
>
> Thanks
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From lina.lastname at gmail.com  Sun Jan 15 14:57:10 2012
From: lina.lastname at gmail.com (lina)
Date: Sun, 15 Jan 2012 21:57:10 +0800
Subject: [Tutor] something about sum, integer and delta function
Message-ID: <CAG9cJmmFXwa29N=sPdOjLfM8VHrTNsKvg9YDvgbNra3ZzUJrwg@mail.gmail.com>

Hi,

are there some modules can be used to do below things like:

sum and delta function, and intergeration.

like the one in attachement.

Thanks,
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Screenshot_2012-01-15-21:55:53.png
Type: image/png
Size: 9247 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120115/117b3eb1/attachment.png>

From fomcl at yahoo.com  Sun Jan 15 15:05:26 2012
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sun, 15 Jan 2012 06:05:26 -0800 (PST)
Subject: [Tutor] something about sum, integer and delta function
In-Reply-To: <CAG9cJmmFXwa29N=sPdOjLfM8VHrTNsKvg9YDvgbNra3ZzUJrwg@mail.gmail.com>
References: <CAG9cJmmFXwa29N=sPdOjLfM8VHrTNsKvg9YDvgbNra3ZzUJrwg@mail.gmail.com>
Message-ID: <1326636326.83497.YahooMailNeo@web110706.mail.gq1.yahoo.com>

Hi,

You could try numpy and scipy.

?
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?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


>________________________________
> From: lina <lina.lastname at gmail.com>
>To: tutor <Tutor at python.org> 
>Sent: Sunday, January 15, 2012 2:57 PM
>Subject: [Tutor] something about sum, integer and delta function
> 
>Hi,
>
>are there some modules can be used to do below things like:
>
>sum and delta function, and intergeration.
>
>like the one in attachement.
>
>Thanks,
>
>_______________________________________________
>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/20120115/58e1af65/attachment.html>

From alan.gauld at btinternet.com  Sun Jan 15 17:34:51 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 15 Jan 2012 16:34:51 +0000
Subject: [Tutor] something about sum, integer and delta function
In-Reply-To: <CAG9cJmmFXwa29N=sPdOjLfM8VHrTNsKvg9YDvgbNra3ZzUJrwg@mail.gmail.com>
References: <CAG9cJmmFXwa29N=sPdOjLfM8VHrTNsKvg9YDvgbNra3ZzUJrwg@mail.gmail.com>
Message-ID: <jeuv7c$8pc$1@dough.gmane.org>

On 15/01/12 13:57, lina wrote:

> are there some modules can be used to do below things like:
>
> sum and delta function, and intergeration.

Not exactly but there are a number of numerical methods that can be used 
to get close approximations. Those have been implemented in a number of 
standard libraries and there are Python wrappers for most of them.

The down side is you really need to understand the math behind them to 
use them effectively. It's not possible to simply translate the example 
expression you gave directly into a Python expression.

For simple summations there are things like sum(), map() and reduce()
And there are other helper functions available like any() and others in 
the itertools module.

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


From steve at pearwood.info  Mon Jan 16 00:21:06 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 16 Jan 2012 10:21:06 +1100
Subject: [Tutor] something about sum, integer and delta function
In-Reply-To: <CAG9cJmmFXwa29N=sPdOjLfM8VHrTNsKvg9YDvgbNra3ZzUJrwg@mail.gmail.com>
References: <CAG9cJmmFXwa29N=sPdOjLfM8VHrTNsKvg9YDvgbNra3ZzUJrwg@mail.gmail.com>
Message-ID: <4F135F62.6070502@pearwood.info>

lina wrote:
> Hi,
> 
> are there some modules can be used to do below things like:
> 
> sum and delta function, and intergeration.
> 
> like the one in attachement.

Try Sage:

http://www.sagemath.org/


-- 
Steven


From ckava1 at msn.com  Mon Jan 16 02:47:13 2012
From: ckava1 at msn.com (Chris Kavanagh)
Date: Sun, 15 Jan 2012 20:47:13 -0500
Subject: [Tutor] Simple Question (I Hope)
In-Reply-To: <CAN2+EpYhGoDA0-mv=-CmRj=99eMEwYHWj_DUT4HM94vq5ZY+iw@mail.gmail.com>
References: <BLU0-SMTP371470DFD22FECC5378A4CC8A820@phx.gbl>
	<CAN2+EpYhGoDA0-mv=-CmRj=99eMEwYHWj_DUT4HM94vq5ZY+iw@mail.gmail.com>
Message-ID: <BLU0-SMTP206A561012BCAD1F67C57378A830@phx.gbl>



On 1/14/2012 11:17 PM, Modulok wrote:
> On 1/14/12, Chris Kavanagh<ckava1 at msn.com>  wrote:
>> I was looking at this code from the Python Docs
>> (http://docs.python.org/library/email-examples.html), trying to learn
>> how to send email from a Pyhton script. Anyways, part of this code
>> confused me. Here's the script:
>>
>> 1 # Import smtplib for the actual sending function
>> 2 import smtplib
>> 3
>> 4 # Import the email modules we'll need
>> 5 from email.mime.text import MIMEText
>> 6
>> 7 # Open a plain text file for reading.  For this example, assume that
>> 8 # the text file contains only ASCII characters.
>> 9 fp = open(textfile, 'rb')
>> 10 # Create a text/plain message
>> 11 msg = MIMEText(fp.read())
>> 12 fp.close()
>> 13
>> 14 # me == the sender's email address
>> 15 # you == the recipient's email address
>> 16 msg['Subject'] = 'The contents of %s' % textfile
>> 17 msg['From'] = me
>> 18 msg['To'] = you
>> 19
>> 20 # Send the message via our own SMTP server, but don't include the
>> 21 # envelope header.
>> 22 s = smtplib.SMTP('localhost')
>> 23 s.sendmail(me, [you], msg.as_string())
>> 24 s.quit()
>>
>> What I don't understand is lines 16-18, more specifically the
>> msg['Subject'] format. I thought this was only done with dics??
>> Obviously the variable msg isn't a dic, so how can this be done??
>>
>> I actually put lines 11, 16,17,18, in the interpreter, then printed out
>> msg, so I get what it's doing, but my question still stands. How can one
>> do this, when I thought it could only be done with dictionaries???
>
> Chris,
>
> I haven't looked at the module, but you should be aware that you can have
> user-defined classes which behave like builtin types, with their own customised
> features. You can also subclass a dict and customise it to do whatever. That
> said, as long as an object provides dictionary access methods, it can be
> treated like a dict in every respect. As far as python is concerned, if it
> looks like a duck and quacks like a duck - it's a duck. (Or in this case a
> dict.) It doesn't matter what the 'type' is, what is important is how you can
> access it.
>
> Here's an example::
>
>
> # example.py
> # The following exapmle could be done more cleanly by subclassing the builtin
> # dict type, but for illustrative purposes this was not done. Instead, we show
> # several dict methods being defined on our dict-like class 'Foo':
>
> class Foo(object):
>      '''This object behaves like a builtin dict that refuses the value "red".'''
>      def __init__(self, x, y):
>          self.x = x  #<-- We can have our own properties too.
>          self.y = y
>          self.data = {}
>
>      def __getitem__(self, key):
>          '''Return 'key' when accessed like self[key]'''
>          return self.data[key]
>
>      def __setitem__(self, key, value):
>          '''Sets self[key] =  value'''
>          if value == "red":
>              raise ValueError("Red is not acceptable!")
>          else:
>              self.data[key] = value
>
>      def items(self):
>          '''These could do whatever you want.'''
>          return self.data.items()
>
>      def keys(self):
>          '''These could do whatever you want.'''
>          return self.data.keys()
>
>      def values(self):
>          '''These could do whatever you want.'''
>          return self.data.values()
>
>
> #===================================================
> # Now let's use it!
> #===================================================
>
> a = Foo(x=3, y=5)
>
> # Is 'a' a dict?
> # False
> print type(a)
>
> # Is it an instance of a dict?
> # False
> print isinstance(a, dict)
>
> # Can we *use* a like a dict?
> a['sky'] =  "orange"
> a['ocean'] = "blue"
>
> for k,v in a.items():
>      print k,v
>
> for v in a.values():
>      print v
>
> ## Yes! Yet, it has it's own set of unique features:
>
> print a.x           #<-- Prints 3
> print a.y           #<-- Prints 5
> a['blood'] = "red"  #<-- Raises exception.
>
>
Thanks for the help. . .I think I see what you're saying. And to make it 
short & simple, the MIMEText Class behaves the way it does, because 
that's just how it works (or was designed). So just accept it, & move 
on, lol.

Thanks again for the reply and the example,it's most appreciated.


From alan.gauld at btinternet.com  Mon Jan 16 09:19:04 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 16 Jan 2012 08:19:04 +0000
Subject: [Tutor] Simple Question (I Hope)
In-Reply-To: <BLU0-SMTP206A561012BCAD1F67C57378A830@phx.gbl>
References: <BLU0-SMTP371470DFD22FECC5378A4CC8A820@phx.gbl>
	<CAN2+EpYhGoDA0-mv=-CmRj=99eMEwYHWj_DUT4HM94vq5ZY+iw@mail.gmail.com>
	<BLU0-SMTP206A561012BCAD1F67C57378A830@phx.gbl>
Message-ID: <jf0mhp$93q$1@dough.gmane.org>

On 16/01/12 01:47, Chris Kavanagh wrote:

> Thanks for the help. . .I think I see what you're saying. And to make it
> short & simple, the MIMEText Class behaves the way it does, because
> that's just how it works (or was designed). So just accept it, & move
> on, lol.

Not quite.
What we are saying is that yhour assumption that only dictionaries 
exhibited mapping behaviour was wrong. Any class can be made to look 
like a dictionary by implementing the set/getitem() methods. So the 
lesson to take away is not just to accept these things but to look under 
the covers to see how such anomolies are possible. Python is a 
wonderfully flexible language because of its combination of duck typing 
and operator overloading.

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


From lie.1296 at gmail.com  Tue Jan 17 03:25:16 2012
From: lie.1296 at gmail.com (Lie Ryan)
Date: Tue, 17 Jan 2012 13:25:16 +1100
Subject: [Tutor] something about sum, integer and delta function
In-Reply-To: <CAG9cJmmFXwa29N=sPdOjLfM8VHrTNsKvg9YDvgbNra3ZzUJrwg@mail.gmail.com>
References: <CAG9cJmmFXwa29N=sPdOjLfM8VHrTNsKvg9YDvgbNra3ZzUJrwg@mail.gmail.com>
Message-ID: <jf2m6d$fiu$1@dough.gmane.org>

On 01/16/2012 12:57 AM, lina wrote:
> Hi,
>
> are there some modules can be used to do below things like:
>
> sum and delta function, and intergeration.

Are you trying to graphically render an equation, calculate the results 
of equation, or algebraically manipulate the equation?


From ckava1 at msn.com  Tue Jan 17 09:07:51 2012
From: ckava1 at msn.com (Chris Kavanagh)
Date: Tue, 17 Jan 2012 03:07:51 -0500
Subject: [Tutor] Reg. Expressions Parenthesis
Message-ID: <BLU0-SMTP686CB1DF9323616A2AAFAF8A800@phx.gbl>

Hey guys, girls, hope everyone is doing well.

Here's my question, when using Regular Expressions, the docs say when 
using parenthesis, it "captures" the data. This has got me confused 
(doesn't take much), can someone explain this to me, please??

Here's an example to use. It's kinda long, so, if you'd rather provide 
your own shorter ex, that'd be fine. Thanks for any help as always.


From: [\w\s]+?<([\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4})>


     From: matches the literal text "From: "
     [\w\s]+? matches one or more consecutive word characters or space 
characters. The question mark makes the match non-greedy, so it will 
match as few characters as possible while still allowing the whole 
regular expression to match (in this case, it's probably not necessary, 
but it does make the match more efficient since the thing that comes 
immediately afterwards is not a word character or space character).
     < matches a literal less-than sign (opening angle bracket)
     The same regular expression you had before (without From: and 
without parenthesis) is now surrounded by parentheses. This makes it a 
capturing group, so you can call m.group(1) to get the text matched by 
that part of the regex.
     > matches a literal greater-than sign

Thanks,
Chris Kavanagh



From waynejwerner at gmail.com  Tue Jan 17 09:48:26 2012
From: waynejwerner at gmail.com (Wayne Werner)
Date: Tue, 17 Jan 2012 03:48:26 -0500
Subject: [Tutor] Reg. Expressions Parenthesis
In-Reply-To: <BLU0-SMTP686CB1DF9323616A2AAFAF8A800@phx.gbl>
References: <BLU0-SMTP686CB1DF9323616A2AAFAF8A800@phx.gbl>
Message-ID: <CAPM86NcF3jTy1kOguUNa0vPjG5MfUJ3Ztr81bY0Uo61-ppzi0Q@mail.gmail.com>

On Tue, Jan 17, 2012 at 3:07 AM, Chris Kavanagh <ckava1 at msn.com> wrote:

> Hey guys, girls, hope everyone is doing well.
>
> Here's my question, when using Regular Expressions, the docs say when
> using parenthesis, it "captures" the data. This has got me confused
> (doesn't take much), can someone explain this to me, please??
>
> Here's an example to use. It's kinda long, so, if you'd rather provide
> your own shorter ex, that'd be fine. Thanks for any help as always.
>

Here's a quick example:

import re

data = 'Wayne Werner fake-phone: 501-555-1234, fake-SSN: 123-12-1234'
parsed = re.search('([\d]{3})-([\d]{3}-[\d]{4})', data)
print(parsed.group())
print(parsed.groups())

parsed = re.search('[\d]{3}-[\d]{3}-[\d]{4}', data)
print(parsed.group())
print(parsed.groups())

You'll notice that you can access the individual clusters using the
.groups() method. This makes capturing the individual groups pretty easy.
Of course, capturing isn't just for storing the results. You can also use
the captured group later on.

Let's say, for some fictitious reason you want to find every letter that
appears as a double in some data. If you were to do this the "brute force"
way you'd pretty much have to do something like this:

for i in range(len(data)-1):
   found = []
   if data[i] == data[i+1]:
      if not data[i] in found:
        found.append(i)
   print(found)

The regex OTOH looks like this:

In [29]: data = 'aaabababbcacacceadbacdb'

In [32]: parsed = re.findall(r'([a-z])\1', data)

In [33]: parsed
Out[33]: ['a', 'b', 'c']

Now, that example was super contrived and also simple. Very few real-world
applications will be as simple as that one - usually you have much crazier
specifications, like find every person who has blue eyes AND blue hair, but
only if they're left handed. Assuming you had data that looked like this:

Name    Eye Color    Hair Color   Handedness     Favorite type of potato
Wayne    Blue             Brown            Dexter             Mashed
Sarah      Blue             Blonde           Sinister            Spam(?)
Kane       Green          White             Dexter             None
Kermit     Blue             Blue               Sinister            Idaho


You could parse out the data using captures and backrefrences [1].

HTH,
Wayne

[1] In this situation, of course, regex is overkill. It's easier to just
.split() and compare. But if you're parsing something really nasty like EDI
then sometimes a regex is just the best way to go[2].

[2] When people start to understand regexes they're like the proverbial man
who only has a hammer. As Jamie Zawinski said[3], "Some people, when
confronted with a problem, think
?I know, I'll use regular expressions.?   Now they have two problems." I've
come across very few occasions that regexes were actually useful, and it's
usually extracting very specifically formatted data (money, phone numbers,
etc.) from copious amounts of text. I've not yet had a need to actually
process words with it. Especially using Python.

[3]http://regex.info/blog/2006-09-15/247
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120117/6633c581/attachment.html>

From mylesbroomes at hotmail.co.uk  Wed Jan 18 00:37:55 2012
From: mylesbroomes at hotmail.co.uk (myles broomes)
Date: Tue, 17 Jan 2012 23:37:55 +0000
Subject: [Tutor] Virtual pet cat program
Message-ID: <DUB102-W273644F6BAA2C1CA1E945F97800@phx.gbl>


I am trying to code a virtual pet cat program. Heres what I have come up with so far:
 
#Pet cat program
#the user chooses a cat of their choice; choosing attributes such as colour, name etc
#the user then has to look after the cat and keep it alive
#create a class for the cat 
class Cat(object):
        """A virtual pet cat"""
        def __init__(self, name, hunger = 5, boredom = 0, tiredness = 0):
                print("Meww!")
                self.name = name
                self.hunger = hunger
                self.boredom = boredom
                self.tiredness = tiredness
        def __str__(self):
                att = "Feline friend\n"
                att += "Name: " + self.name + "\n"
                if self.hunger >= 2:
                        print("Your pet is hungry.")
                elif self.boredom >= 2:
                        print("Your pet is bored.")
                elif self.tiredness >= 2:
                        print("Your pet is tired.")
                return att
        def __pass_time(self):
                self.hunger += 1
                self.boredom += 1
                self.tiredness += 1
        def eat(self, food = 5):
                print("Purrrr purrr!")
                self.hunger -= food
                if self.hunger < 0:
                        self.hunger = 0
                self.__pass_time()
        def play(self, fun = 5):
                print("Chirrup!")
                self.boredom -= fun
                if self.boredom < 0:
                        self.boredom = 0
                self.__pass_time()
        def rest(self, sleep = 5):
                print("...")
                self.tiredness -= sleep
                if self.tiredness < 0:
                        self.tiredness = 0
                self.__pass_time()
#introduce and explain the program to the user
input("Welcome to the pet cat simulation program. You will get the opportunity to look after a cat of choice. Press enter to begin.")
#get the users chosen attributes for their cat
name = input("Please enter a name for your cat: ")
user_cat = Cat(name)
#taking care of the cat loop
choice = None
while choice != "0":
        print("What would you like to do? (Enter 1 to feed the cat, enter 2 to play with the cat, enter 3 to leave the cat to rest or press 0 to exit the program.")
        choice = input(">")
        if choice == "1":
                user_cat.eat
                print(user_cat)
        elif choice == "2":
                user_cat.play
                print(user_cat)
        elif choice == "3":
                user_cat.rest
                print(user_cat)
input("Press enter to exit...") 
 
...Then I try to run the program:
 
Welcome to the pet cat simulation program. You will get the opportunity to look after a cat of choice. Press enter to begin.
Please enter a name for your cat: X
Meww!
What would you like to do? (Enter 1 to feed the cat, enter 2 to play with the cat, enter 3 to leave the cat to rest or press 0 to exit the program.
>1
Your pet is hungry.
Feline friend
Name: X
What would you like to do? (Enter 1 to feed the cat, enter 2 to play with the cat, enter 3 to leave the cat to rest or press 0 to exit the program.
>1
Your pet is hungry.
Feline friend
Name: X
What would you like to do? (Enter 1 to feed the cat, enter 2 to play with the cat, enter 3 to leave the cat to rest or press 0 to exit the program.
>1
Your pet is hungry.
Feline friend
Name: X
What would you like to do? (Enter 1 to feed the cat, enter 2 to play with the cat, enter 3 to leave the cat to rest or press 0 to exit the program.
>1
Your pet is hungry.
Feline friend
Name: X
What would you like to do? (Enter 1 to feed the cat, enter 2 to play with the cat, enter 3 to leave the cat to rest or press 0 to exit the program.
>0
Press enter to exit...
 
As you can see, no matter how many times I 'feed' the cat, its always hungry. Can someone please tell me why it wont update? 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120117/e5ec4024/attachment.html>

From ramit.prasad at jpmorgan.com  Wed Jan 18 00:51:47 2012
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Tue, 17 Jan 2012 23:51:47 +0000
Subject: [Tutor] Virtual pet cat program
In-Reply-To: <DUB102-W273644F6BAA2C1CA1E945F97800@phx.gbl>
References: <DUB102-W273644F6BAA2C1CA1E945F97800@phx.gbl>
Message-ID: <5B80DD153D7D744689F57F4FB69AF4740CAD67@SCACMX008.exchad.jpmchase.net>

>As you can see, no matter how many times I 'feed' the cat, its always hungry. Can someone please tell me why it wont update?

>while choice != "0":
>        print("What would you like to do? (Enter 1 to feed the cat, enter 2 to play with the cat, enter 3 to leave the cat to rest or press 0 to exit the program.")
>        choice = input(">")
>        if choice == "1":
>                user_cat.eat
>                print(user_cat)
>        elif choice == "2":
>                user_cat.play
>                print(user_cat)
>        elif choice == "3":
>                user_cat.rest
>                print(user_cat)

You are not calling the function, just referring to it. 

>>> user_cat.eat
<bound method Cat.eat of <__pieshell__.Cat object at 0x095E7C10>>

You should be calling user_cat.eat() or user_cat.eat( 10 ) to actually perform the action you desire.


Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From stayvoid at gmail.com  Wed Jan 18 03:13:34 2012
From: stayvoid at gmail.com (Stayvoid)
Date: Wed, 18 Jan 2012 05:13:34 +0300
Subject: [Tutor] Class vs. instance
In-Reply-To: <CAK5fS_Gpo8unEjq3mz7dD2WuCSMO-Tei-6Vh_kHOOafT4cZXNw@mail.gmail.com>
References: <CAK5fS_FDj8no7+nEUma0EwAFOgXd=548p17j4E2zqiD2oKZ+Yg@mail.gmail.com>
	<CAJmBOfkGSLbMBrdd3=cOjMoPrWDVZMZ_u3SNSGZqiWgXvV1LSw@mail.gmail.com>
	<CAK5fS_Gpo8unEjq3mz7dD2WuCSMO-Tei-6Vh_kHOOafT4cZXNw@mail.gmail.com>
Message-ID: <CAK5fS_HHXW4aoGN9M7jAifhuSXG8UUjFaYTxt_6n4oKJk5o_nw@mail.gmail.com>

Hello!

Here is another one.

class A:
	def __init__(self, data):
		self.data = data
		print self.data

I'm trying to understand this function-like syntax:
A('foo').__init__(42)
A(12).data

What are we actually calling this way?
Are there any other ways to get the same result?


Cheers.

From d at davea.name  Wed Jan 18 03:34:42 2012
From: d at davea.name (Dave Angel)
Date: Tue, 17 Jan 2012 21:34:42 -0500
Subject: [Tutor] Class vs. instance
In-Reply-To: <CAK5fS_HHXW4aoGN9M7jAifhuSXG8UUjFaYTxt_6n4oKJk5o_nw@mail.gmail.com>
References: <CAK5fS_FDj8no7+nEUma0EwAFOgXd=548p17j4E2zqiD2oKZ+Yg@mail.gmail.com>	<CAJmBOfkGSLbMBrdd3=cOjMoPrWDVZMZ_u3SNSGZqiWgXvV1LSw@mail.gmail.com>	<CAK5fS_Gpo8unEjq3mz7dD2WuCSMO-Tei-6Vh_kHOOafT4cZXNw@mail.gmail.com>
	<CAK5fS_HHXW4aoGN9M7jAifhuSXG8UUjFaYTxt_6n4oKJk5o_nw@mail.gmail.com>
Message-ID: <4F162FC2.9070307@davea.name>

On 01/17/2012 09:13 PM, Stayvoid wrote:
> Hello!
>
> Here is another one.
>
> class A:
> 	def __init__(self, data):
> 		self.data = data
> 		print self.data
>
> I'm trying to understand this function-like syntax:
> A('foo').__init__(42)
> A(12).data
>
> What are we actually calling this way?
> Are there any other ways to get the same result?
The first line creates an instance of class A, then immediately calls 
the method __init__() as though it were a normal function.  It then 
discards the object.

You should only call __init__() from within another class' __init__().  
It's called automatically when an object is created;  leave it at that.

You also usually want to keep the instance around, and use it more than 
once.  Otherwise you could just use ordinary functions and dispense with 
the confusion.

A(12) creates an object, then you reference the data attribute of that 
object, then you throw them both out.  Not much use there either.

Try  something like:

obj= A(49)
print obj.data
obj2 = A("artichoke")
obj.data = 99
print obj.data
print obj2.data

Two more things.  Remove the print statement from methods like 
__init__(), unless it's just for debugging purposes.  And add a base 
class of object to your class definition, so that a new-style class is 
created.  When you get to more advanced usage, it'll make a difference, 
and you might as well use the version of class that'll still work in 
Python 3.x.

class A(object):
      .....



-- 

DaveA


From ckava1 at msn.com  Wed Jan 18 05:23:20 2012
From: ckava1 at msn.com (Chris Kavanagh)
Date: Tue, 17 Jan 2012 23:23:20 -0500
Subject: [Tutor] Reg Ex Parentheses
Message-ID: <BLU0-SMTP2847C2354C15C0206C4470D8A810@phx.gbl>

Hey guys, girls, hope everyone is doing well.

Here's my question, when using Regular Expressions, the docs say when 
using parenthesis, it "captures" the data. This has got me confused 
(doesn't take much), can someone explain this to me, please??

Here's an example to use. It's kinda long, so, if you'd rather provide 
your own shorter ex, that'd be fine. Thanks for any help as always.


From: [\w\s]+?<([\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4})>


     From: matches the literal text "From: "
     [\w\s]+? matches one or more consecutive word characters or space 
characters. The question mark makes the match non-greedy, so it will 
match as few characters as possible while still allowing the whole 
regular expression to match (in this case, it's probably not necessary, 
but it does make the match more efficient since the thing that comes 
immediately afterwards is not a word character or space character).
     < matches a literal less-than sign (opening angle bracket)
     The same regular expression you had before (without From: and 
without parenthesis) is now surrounded by parentheses. This makes it a 
capturing group, so you can call m.group(1) to get the text matched by 
that part of the regex.
     > matches a literal greater-than sign

Thanks,
Chris Kavanagh


From alan.gauld at btinternet.com  Wed Jan 18 09:52:28 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 18 Jan 2012 08:52:28 +0000
Subject: [Tutor] Class vs. instance
In-Reply-To: <CAK5fS_HHXW4aoGN9M7jAifhuSXG8UUjFaYTxt_6n4oKJk5o_nw@mail.gmail.com>
References: <CAK5fS_FDj8no7+nEUma0EwAFOgXd=548p17j4E2zqiD2oKZ+Yg@mail.gmail.com>
	<CAJmBOfkGSLbMBrdd3=cOjMoPrWDVZMZ_u3SNSGZqiWgXvV1LSw@mail.gmail.com>
	<CAK5fS_Gpo8unEjq3mz7dD2WuCSMO-Tei-6Vh_kHOOafT4cZXNw@mail.gmail.com>
	<CAK5fS_HHXW4aoGN9M7jAifhuSXG8UUjFaYTxt_6n4oKJk5o_nw@mail.gmail.com>
Message-ID: <jf618c$jju$1@dough.gmane.org>

On 18/01/12 02:13, Stayvoid wrote:

> class A:
> 	def __init__(self, data):
> 		self.data = data
> 		print self.data
>
> I'm trying to understand this function-like syntax:
> A('foo').__init__(42)

You would not normally call any method with a double underscore 
pre/poist fix because they are special methods called by Python
itself. Thus when you do

A('foo')

Python actually calls two special methods on class A. First it calls the 
__new__() method to create an instance of A then it calls __init__() 
with 'foo' as argument to initialise that instance. You don't need to 
call init() directly. In fact it may even cause problems if you 
initialise a class twice.

So when you do

A('foo').__init__(42)

You actually do 3 things:
First you create a new instance of A, then you initialise it with 'foo' 
then you initialise it again with 42. In this case no harm is done 
because the init)() method just does a double assignment, losing the 
initial value. But if you were storing the data values in a lkist you 
would wind up with two values instead of one, which may not be a good thing.

> A(12).data

Here you create another instance of A and initialise it with 12 then you 
access its data attribute. If you do this in the interpreter the value 
of data will be printed, if you do it in a program nothing will happen.

In both iof the cases above the newly created instances will be garbage 
collected since they were not assigned to any variable.

> What are we actually calling this way?

You call the constructor __new__(), the initialiser __init__()
and you access a data item which calls the accessor __getattr__()

> Are there any other ways to get the same result?

It depends how you define 'the same results'.
The same end state can be achieved in several ways.
The same methods can be called in several ways, for example
you can call init via the class:

anAinstance = A('foo')
A.__init__(anAinstance, 42)

But in general all of these are a bad idea outside of
a class/method definition. Don't do it.

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


From kushal.kumaran+python at gmail.com  Wed Jan 18 11:58:03 2012
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Wed, 18 Jan 2012 16:28:03 +0530
Subject: [Tutor] Reg Ex Parentheses
In-Reply-To: <BLU0-SMTP2847C2354C15C0206C4470D8A810@phx.gbl>
References: <BLU0-SMTP2847C2354C15C0206C4470D8A810@phx.gbl>
Message-ID: <CAH8GtdNBk+TumSwxdVA5DJTqjmnEYOcXKCoXfQC32=9R7Ef38g@mail.gmail.com>

On Wed, Jan 18, 2012 at 9:53 AM, Chris Kavanagh <ckava1 at msn.com> wrote:
> Hey guys, girls, hope everyone is doing well.
>
> Here's my question, when using Regular Expressions, the docs say when using
> parenthesis, it "captures" the data. This has got me confused (doesn't take
> much), can someone explain this to me, please??
>
> Here's an example to use. It's kinda long, so, if you'd rather provide your
> own shorter ex, that'd be fine. Thanks for any help as always.
>

"Capturing" means that the part of the string that was matched is
remembered, so you can extract parts of a string.  Here's a small
example that extracts the name and value part of a name=value style
string.  Note the use of parentheses, and the calls to the "group"
method of the match object.

the_string = 'A=B'
pair_re = re.compile("""^       # starting from the start of the string
                        ([^=]*) # sequence of characters not containing equals
                        =       # the literal equals sign
                        (.*)    # everything until...
                        $       # end of string
                      """, re.VERBOSE)
match_obj = pair_re.match(the_string)
print('Captured name was {}'.format(match_obj.group(1)))
print('Captured value was {}'.format(match_obj.group(2)))

-- 
regards,
kushal

From smileham at vodamail.co.za  Wed Jan 18 13:00:49 2012
From: smileham at vodamail.co.za (Selwyn Mileham)
Date: Wed, 18 Jan 2012 14:00:49 +0200
Subject: [Tutor] (no subject)
Message-ID: <000101ccd5d8$d387b400$7a971c00$@co.za>

Help someone

Trying to print to printer using python 3.2.2

Get error load dll error can't find win32print.

It is in site library 

Thanks

 

Selwyn

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

From waynejwerner at gmail.com  Wed Jan 18 14:18:37 2012
From: waynejwerner at gmail.com (Wayne Werner)
Date: Wed, 18 Jan 2012 07:18:37 -0600
Subject: [Tutor] (no subject)
In-Reply-To: <000101ccd5d8$d387b400$7a971c00$@co.za>
References: <000101ccd5d8$d387b400$7a971c00$@co.za>
Message-ID: <CAPM86NcEJF6Sb=se_FMZyURxuojee-21=khY25ac=dJzBTSEsw@mail.gmail.com>

On Wed, Jan 18, 2012 at 6:00 AM, Selwyn Mileham <smileham at vodamail.co.za>wrote:

>  Help someone****
>
> Trying to print to printer using python 3.2.2****
>
> Get error load dll error can?t find win32print.****
>
> It is in site library
>

What have you tried? If you get an exception, please post the exact text of
the traceback. If the code you used is short enough then it's reasonable to
just paste it in your email (make sure HTML formatting is off, though,
because it will probably break the formatting).

-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120118/3d2f1815/attachment.html>

From suryak at live.com  Wed Jan 18 14:34:37 2012
From: suryak at live.com (karthik s)
Date: Wed, 18 Jan 2012 19:04:37 +0530
Subject: [Tutor] Facebook apps with python
Message-ID: <SNT130-W63F504B90A6271F0CD46AEA4810@phx.gbl>


Well, my question is simple.. 
How do I create facebook apps with python. I have couple of interesting/ funky programs and want to make them as apps.
So, 
1. What all things I should know for writing facebook apps.
2. I read that we should first upload our app to 'google app engine' and need do link it to facebook.. Is that right?
3. Actually, I am not aware of Network/ Web programming.. can I be able to do that?
4. Please do mention a couple of books (ebooks) from which I can learn.. That will help me.  		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120118/29bf94d2/attachment.html>

From ranjithtenz at gmail.com  Wed Jan 18 14:48:59 2012
From: ranjithtenz at gmail.com (Ranjith Kumar)
Date: Wed, 18 Jan 2012 19:18:59 +0530
Subject: [Tutor] Facebook apps with python
In-Reply-To: <SNT130-W63F504B90A6271F0CD46AEA4810@phx.gbl>
References: <SNT130-W63F504B90A6271F0CD46AEA4810@phx.gbl>
Message-ID: <CAAr0NR-ru5VT3w0igR5he8YTzDWzZC=ariZtn6psy6jHB1xBaw@mail.gmail.com>

Please try this karthik
https://www.google.com/search?client=ubuntu&channel=fs&q=how+to+create+facebook+app+using+python&ie=utf-8&oe=utf-8

On Wed, Jan 18, 2012 at 7:04 PM, karthik s <suryak at live.com> wrote:

>  Well, my question is simple..
>
> How do I create facebook apps with python. I have couple of interesting/
> funky programs and want to make them as apps.
>
> So,
>
> 1. What all things I should know for writing facebook apps.
>
> 2. I read that we should first upload our app to 'google app engine' and
> need do link it to facebook.. Is that right?
>
> 3. Actually, I am not aware of Network/ Web programming.. can I be able to
> do that?
>
> 4. Please do mention a couple of books (ebooks) from which I can learn..
> That will help me.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Cheers,
Ranjith Kumar K,
Chennai.

http://ranjithtenz.wordpress.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120118/d2bb263d/attachment.html>

From alan.gauld at btinternet.com  Wed Jan 18 14:49:01 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 18 Jan 2012 13:49:01 +0000
Subject: [Tutor] (no subject)
In-Reply-To: <000101ccd5d8$d387b400$7a971c00$@co.za>
References: <000101ccd5d8$d387b400$7a971c00$@co.za>
Message-ID: <jf6ikd$336$1@dough.gmane.org>

On 18/01/12 12:00, Selwyn Mileham wrote:

> Trying to print to printer using python 3.2.2
>
> Get error load dll error can?t find win32print.

So what are you trying?
You don't give us much to work with here?

Also you're more likely to get an answer from one of
the Python windows lists rather than one dedicated to
teaching the Python language. But without knowing how
you are trying to print (wxPython, ctypes, pythonwin,
other???) it's impossible to direct you to the best place.

Can you show us a short piece of code that exhibits the problem
and the full error trace?

HTH

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


From alan.gauld at btinternet.com  Wed Jan 18 14:54:41 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 18 Jan 2012 13:54:41 +0000
Subject: [Tutor] Facebook apps with python
In-Reply-To: <SNT130-W63F504B90A6271F0CD46AEA4810@phx.gbl>
References: <SNT130-W63F504B90A6271F0CD46AEA4810@phx.gbl>
Message-ID: <jf6iv1$5m9$1@dough.gmane.org>

On 18/01/12 13:34, karthik s wrote:
> Well, my question is simple..
>
> How do I create facebook apps with python.

I have no idea, I never use Facebook.
But given this is a list for peiople learning the
Python language  it might be too specialised a
question, you might be better on the general Python
list.

However, here goes a starting point...


> 1. What all things I should know for writing facebook apps.

No idea on this one.

> 2. I read that we should first upload our app to 'google app engine' and
> need do link it to facebook.. Is that right?

Do you know about the Google App Engine? Thats a whole topic in itself. 
You probbably need to visit Google and do some digging there.

> 3. Actually, I am not aware of Network/ Web programming.. can I be able
> to do that?

You can do general network/web programming in Python. But if using 
Google is necessary then it's not going to be that standard...

> 4. Please do mention a couple of books (ebooks) from which I can learn..
> That will help me.

What is your starting point?
Are you a complete beginner to programming?
Can you program already in another language?
Can you program already in Python?
What OS and Python version are you using?

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


From lina.lastname at gmail.com  Wed Jan 18 15:56:55 2012
From: lina.lastname at gmail.com (lina)
Date: Wed, 18 Jan 2012 22:56:55 +0800
Subject: [Tutor] something about sum, integer and delta function
In-Reply-To: <jf2m6d$fiu$1@dough.gmane.org>
References: <CAG9cJmmFXwa29N=sPdOjLfM8VHrTNsKvg9YDvgbNra3ZzUJrwg@mail.gmail.com>
	<jf2m6d$fiu$1@dough.gmane.org>
Message-ID: <CAG9cJmmLU2y=f5rLU=V+EaucS7q=3qVC=QYQGjr6wh7eZxvY7w@mail.gmail.com>

On Tue, Jan 17, 2012 at 10:25 AM, Lie Ryan <lie.1296 at gmail.com> wrote:
> On 01/16/2012 12:57 AM, lina wrote:
>>
>> Hi,
>>
>> are there some modules can be used to do below things like:
>>
>> sum and delta function, and intergeration.
>
>
> Are you trying to graphically render an equation, calculate the results of
> equation, or algebraically manipulate the equation?

It's involved a series of derivation process. a bit big project. I
will come back later once my programming gets a bit mature. at present
too heavy for me.

Thanks all

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

From PDowney at urban.org  Wed Jan 18 19:07:16 2012
From: PDowney at urban.org (Downey, Patrick)
Date: Wed, 18 Jan 2012 13:07:16 -0500
Subject: [Tutor] Installing Modules
Message-ID: <0F96478603980B46AAAFBA77069582ED18B39A4F@UIEXCH.urban.org>

Hello,

I'll start by saying that I have a math/stats background, not a computer
science one. I've found lots of great material to help with Python
programming, but have had a much harder time getting my head around setup
issues, like installing modules.

I'm currently running Python version 2.7 through IDLE on a Windows machine.
I'm trying to use numpy and scipy. I downloaded both modules from the scipy
website and unzipped the files into:
C:\Python27\Lib\site-packages

I try to load them using this at the beginning of my program.
from numpy import *
from scipy import *

And I get this error:
Traceback (most recent call last):
  File "D:/Documents and Settings/pdowney/My Documents/Actual
Projects/Foreclosures/Python/Program (1-18-12).py", line 3, in <module>
    from scipy import *
ImportError: No module named scipy

Numpy loads just fine. Both are in the same folder. That is, there's a file
called setup.py in the folder:
C:\Python27\Lib\site-packages\numpy

And also in the folder:
C:\Python27\Lib\site-packages\scipy

I don't understand what is being done differently between the two packages.
According to Chapter 6 of the Python documentation, "When a module named
spam is imported, the interpreter searches for a file named spam.py in the
directory containing the input script and then in the list of directories
specified by the environment variable PYTHONPATH." Unfortunately, I haven't
figured out how to look at PYTHONPATH, so I don't know where it's looking.
>>> print PYTHONPATH
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    print PYTHONPATH
NameError: name 'PYTHONPATH' is not defined

Importantly, there is no file scipy.py in the scipy folder, as the
documentation suggests there should be, but there's also no numpy.py in the
numpy folder and that module loads successfully. Clearly I'm missing
something in the setup of these modules. Any guidance would be greatly
appreciated.

Thank you,
Mitch

From defensoft at gmail.com  Wed Jan 18 19:15:25 2012
From: defensoft at gmail.com (Nate Lastname)
Date: Wed, 18 Jan 2012 13:15:25 -0500
Subject: [Tutor] Installing Modules
In-Reply-To: <0F96478603980B46AAAFBA77069582ED18B39A4F@UIEXCH.urban.org>
References: <0F96478603980B46AAAFBA77069582ED18B39A4F@UIEXCH.urban.org>
Message-ID: <CABe2FwrcvKK4sdOUTeft2KzwPUu-HgE4fapU=LEWKq07qTkuJA@mail.gmail.com>

Have you looked at help(sys)?  sys stores the PYTHONPATH variable.  Just run
>>> import sys
>>> help(sys)
at the python prompt.

On 1/18/12, Downey, Patrick <PDowney at urban.org> wrote:
> Hello,
>
> I'll start by saying that I have a math/stats background, not a computer
> science one. I've found lots of great material to help with Python
> programming, but have had a much harder time getting my head around setup
> issues, like installing modules.
>
> I'm currently running Python version 2.7 through IDLE on a Windows machine.
> I'm trying to use numpy and scipy. I downloaded both modules from the scipy
> website and unzipped the files into:
> C:\Python27\Lib\site-packages
>
> I try to load them using this at the beginning of my program.
> from numpy import *
> from scipy import *
>
> And I get this error:
> Traceback (most recent call last):
>   File "D:/Documents and Settings/pdowney/My Documents/Actual
> Projects/Foreclosures/Python/Program (1-18-12).py", line 3, in <module>
>     from scipy import *
> ImportError: No module named scipy
>
> Numpy loads just fine. Both are in the same folder. That is, there's a file
> called setup.py in the folder:
> C:\Python27\Lib\site-packages\numpy
>
> And also in the folder:
> C:\Python27\Lib\site-packages\scipy
>
> I don't understand what is being done differently between the two packages.
> According to Chapter 6 of the Python documentation, "When a module named
> spam is imported, the interpreter searches for a file named spam.py in the
> directory containing the input script and then in the list of directories
> specified by the environment variable PYTHONPATH." Unfortunately, I haven't
> figured out how to look at PYTHONPATH, so I don't know where it's looking.
>>>> print PYTHONPATH
> Traceback (most recent call last):
>   File "<pyshell#17>", line 1, in <module>
>     print PYTHONPATH
> NameError: name 'PYTHONPATH' is not defined
>
> Importantly, there is no file scipy.py in the scipy folder, as the
> documentation suggests there should be, but there's also no numpy.py in the
> numpy folder and that module loads successfully. Clearly I'm missing
> something in the setup of these modules. Any guidance would be greatly
> appreciated.
>
> Thank you,
> Mitch
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
My Blog - Defenestration Coding

http://defenestrationcoding.wordpress.com/

From alan.gauld at btinternet.com  Wed Jan 18 19:24:22 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 18 Jan 2012 18:24:22 +0000
Subject: [Tutor] Installing Modules
In-Reply-To: <0F96478603980B46AAAFBA77069582ED18B39A4F@UIEXCH.urban.org>
References: <0F96478603980B46AAAFBA77069582ED18B39A4F@UIEXCH.urban.org>
Message-ID: <jf72om$2ql$1@dough.gmane.org>

On 18/01/12 18:07, Downey, Patrick wrote:

> I'm trying to use numpy and scipy.

I'll leave those specifics to those who use them, but...

> specified by the environment variable PYTHONPATH." Unfortunately, I haven't
> figured out how to look at PYTHONPATH, so I don't know where it's looking.


Do it at the Windows level.
The easiest way to see it is probably to start a CMD window and type SET 
PYTHONPATH
at the C:\WINDOWS> (or whatever path it reads) prompt.

You can also do it by:

Assuming you are using Win2000 or XP you do that by right clicking My 
Computer and selecting Properties. Go to Advanced and click Environment 
Variables. Look for the PYTHONPATH one in the list and select it.

Vista and Win7 might vary slightly...

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


From malaclypse2 at gmail.com  Wed Jan 18 20:01:12 2012
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Wed, 18 Jan 2012 14:01:12 -0500
Subject: [Tutor] Installing Modules
In-Reply-To: <0F96478603980B46AAAFBA77069582ED18B39A4F@UIEXCH.urban.org>
References: <0F96478603980B46AAAFBA77069582ED18B39A4F@UIEXCH.urban.org>
Message-ID: <CADwdpyadyf0DGhKQAQP6JQ2NeRyN5i0u2rGvmA=K5r=dh+GswQ@mail.gmail.com>

On Wed, Jan 18, 2012 at 1:07 PM, Downey, Patrick <PDowney at urban.org> wrote:

> I'm currently running Python version 2.7 through IDLE on a Windows machine.
> I'm trying to use numpy and scipy. I downloaded both modules from the scipy
> website and unzipped the files into:
> C:\Python27\Lib\site-packages
>

That is not the typical way to install software on windows, even python
modules.  Typically, software on windows is distributed in an installer.
Numpy and Scipy are the same way.  You could download the source code,
compile it, and install it from there, but that's pretty unusual on windows.

So.  Remove whatever you have unzipped into site-packages.  Download the
numpy and scipy installers.  Run them.  That should be it.

Numpy installer:
http://sourceforge.net/projects/numpy/files/NumPy/1.6.1/numpy-1.6.1-win32-superpack-python2.7.exe/download

Scipy installer:
http://sourceforge.net/projects/scipy/files/scipy/0.10.0/scipy-0.10.0-win32-superpack-python2.7.exe/download

If you really do want to compile scipy and numpy from source, there are
instructions on getting all the required tools here:
http://scipy.org/Installing_SciPy/Windows

-- 
Jerry

PS: There *are* python packages out there that have to just be unzipped
into site-packages.  Those projects are typically pure-python modules
without any C code to compile.  Numpy and Scipy aren't among them, though.
There are other packages that expect you to download them, extract them to
a temp directory, then run "python setup.py install".   To know for sure
how to install a particular package, you'll need to dig around a bit for
installation instructions for that particular package.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120118/84fc4484/attachment.html>

From wprins at gmail.com  Wed Jan 18 20:01:57 2012
From: wprins at gmail.com (Walter Prins)
Date: Wed, 18 Jan 2012 19:01:57 +0000
Subject: [Tutor] Installing Modules
In-Reply-To: <0F96478603980B46AAAFBA77069582ED18B39A4F@UIEXCH.urban.org>
References: <0F96478603980B46AAAFBA77069582ED18B39A4F@UIEXCH.urban.org>
Message-ID: <CANLXbfD7gyF=J7f8Od787bX5t+2H5HXt18j2wmRhhvZ8Ux9eGA@mail.gmail.com>

Hi,

On 18 January 2012 18:07, Downey, Patrick <PDowney at urban.org> wrote:

> I'm currently running Python version 2.7 through IDLE on a Windows machine.
> I'm trying to use numpy and scipy. I downloaded both modules from the scipy
> website and unzipped the files into:
> C:\Python27\Lib\site-packages
>

Generally, manually installing modules/packages into site-packages should
be the last option you choose for installing 3rd party modules/packages
into your Python environment.  For Windows machines, you should, in order
of preference (IMHO) choose:
1.) A customer installer package (.exe. file or .msi file) built for your
specific bit version of Windows (ie 32 or 64 bit) and for your specific
version of Python (e.g. 2.7, 3.2 etc.)
2.) Install via Python's generic package management support e.g. via one of:
distribute
pip
setuptools
These tools make it trivial to install most non-platform-specific modules
from a central repository using a single command, removing the need to know
where to get them or how to install them.
3.) Direct installation via an included "setup.py" script:  Most Python
packages include an installation script intended to install the package
into your Python environment correctly, usually via the command:
python setup.py install
4.) Manually copying/installing into your Python environment.

In your case, there are Windows .exe based installers available for Windows
32 bit for Python 2.7 for both SciPy and NumPy so I'd suggest you remove
your manual attempts and re-install using one of the pre-built installers.

HTH,

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120118/5af8e1bf/attachment-0001.html>

From ckava1 at msn.com  Thu Jan 19 01:09:12 2012
From: ckava1 at msn.com (Chris Kavanagh)
Date: Wed, 18 Jan 2012 19:09:12 -0500
Subject: [Tutor] To: Wayne Werner , re  Reg. Expressions Parenthesis
Message-ID: <BLU0-SMTP415CD5C5109B084BE3B10668A860@phx.gbl>

For some reason I didn't get this email, found it in the archives. I 
wanted to make sure I thanked Wayne for the help!!!




On Tue, Jan 17, 2012 at 3:07 AM, Chris Kavanagh <[hidden email]> wrote:
Hey guys, girls, hope everyone is doing well.

Here's my question, when using Regular Expressions, the docs say when 
using parenthesis, it "captures" the data. This has got me confused 
(doesn't take much), can someone explain this to me, please??

Here's an example to use. It's kinda long, so, if you'd rather provide 
your own shorter ex, that'd be fine. Thanks for any help as always.

Here's a quick example:

import re

data = 'Wayne Werner fake-phone: 501-555-1234, fake-SSN: 123-12-1234'
parsed = re.search('([\d]{3})-([\d]{3}-[\d]{4})', data)
print(parsed.group())
print(parsed.groups())

parsed = re.search('[\d]{3}-[\d]{3}-[\d]{4}', data)
print(parsed.group())
print(parsed.groups())

You'll notice that you can access the individual clusters using the 
.groups() method. This makes capturing the individual groups pretty 
easy. Of course, capturing isn't just for storing the results. You can 
also use the captured group later on.

Let's say, for some fictitious reason you want to find every letter that 
appears as a double in some data. If you were to do this the "brute 
force" way you'd pretty much have to do something like this:

for i in range(len(data)-1):
    found = []
    if data[i] == data[i+1]:
       if not data[i] in found:
         found.append(i)
    print(found)

The regex OTOH looks like this:

In [29]: data = 'aaabababbcacacceadbacdb'

In [32]: parsed = re.findall(r'([a-z])\1', data)

In [33]: parsed
Out[33]: ['a', 'b', 'c']

Now, that example was super contrived and also simple. Very few 
real-world applications will be as simple as that one - usually you have 
much crazier specifications, like find every person who has blue eyes 
AND blue hair, but only if they're left handed. Assuming you had data 
that looked like this:

Name    Eye Color    Hair Color   Handedness     Favorite type of potato
Wayne    Blue             Brown            Dexter             Mashed
Sarah      Blue             Blonde           Sinister            Spam(?)
Kane       Green          White             Dexter             None
Kermit     Blue             Blue               Sinister            Idaho


You could parse out the data using captures and backrefrences [1].

HTH,
Wayne

[1] In this situation, of course, regex is overkill. It's easier to just 
.split() and compare. But if you're parsing something really nasty like 
EDI then sometimes a regex is just the best way to go[2].

[2] When people start to understand regexes they're like the proverbial 
man who only has a hammer. As Jamie Zawinski said[3], "Some people, when 
confronted with a problem, think
?I know, I'll use regular expressions.?   Now they have two problems." 
I've come across very few occasions that regexes were actually useful, 
and it's usually extracting very specifically formatted data (money, 
phone numbers, etc.) from copious amounts of text. I've not yet had a 
need to actually process words with it. Especially using Python.

[3]http://regex.info/blog/2006-09-15/247

_______________________________________________
Tutor maillist  -  [hidden email]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Thanks again Wayne.

From sp6 at rice.edu  Thu Jan 19 06:49:59 2012
From: sp6 at rice.edu (sp6 at rice.edu)
Date: Wed, 18 Jan 2012 23:49:59 -0600
Subject: [Tutor] Question about install.py
Message-ID: <20120118234959.164771p8h7coitqf@webmail.rice.edu>

Hello,

I'm new to Python and was wondering if someone could answer a question I have.
Say that I have a python library, arithmetic-0.5, located at /X/arithmetic-0.5
I'd like to run setup and install it. But I guess since  
/X/arithmetic-0.5 is not in install.py's default search path, it comes  
back with an error saying that it cannot find the necessary files.
Can you please tell me how I can change the search path of install.py?  
What parameter do I need to modify?

Thanks in advance.




From jasonloeve at gmail.com  Thu Jan 19 14:02:41 2012
From: jasonloeve at gmail.com (Jason Loeve)
Date: Thu, 19 Jan 2012 15:02:41 +0200
Subject: [Tutor] help with program from learning python the hard way
Message-ID: <CANZF_8HOzDxt=Sk5++EjOfn3EbQ7L97ua+HjQxQfHtGohWN04w@mail.gmail.com>

good day i seem to be stuck, my code is

from sys import argv

script, user_name = argv

and i get an error ValueError: need more than 1 value to unpack

http://learnpythonthehardway.org/book/ex14.html

i am using PyCharm 1.5.4 to run

thanks in advance
jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120119/3b30834b/attachment.html>

From dextrous85 at gmail.com  Thu Jan 19 14:14:53 2012
From: dextrous85 at gmail.com (vishwajeet singh)
Date: Thu, 19 Jan 2012 18:44:53 +0530
Subject: [Tutor] help with program from learning python the hard way
In-Reply-To: <CANZF_8HOzDxt=Sk5++EjOfn3EbQ7L97ua+HjQxQfHtGohWN04w@mail.gmail.com>
References: <CANZF_8HOzDxt=Sk5++EjOfn3EbQ7L97ua+HjQxQfHtGohWN04w@mail.gmail.com>
Message-ID: <CACbucK=APWywQJYEC5ct7Ziq_4+mkLB4OV9=vphETyvitKn-Zw@mail.gmail.com>

On Thu, Jan 19, 2012 at 6:32 PM, Jason Loeve <jasonloeve at gmail.com> wrote:

> good day i seem to be stuck, my code is
>
> from sys import argv
>
> script, user_name = argv
>

Are you  passing an additional parameter while executing the script ?? you
must execute it passing an additional parameter which will get assigned to
user_name


> and i get an error ValueError: need more than 1 value to unpack
>
> http://learnpythonthehardway.org/book/ex14.html
>
> i am using PyCharm 1.5.4 to run
>
> thanks in advance
> jason
>
>
>
> _______________________________________________
> 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/20120119/291b6bf0/attachment.html>

From bodsda at googlemail.com  Thu Jan 19 14:17:21 2012
From: bodsda at googlemail.com (bodsda at googlemail.com)
Date: Thu, 19 Jan 2012 13:17:21 +0000
Subject: [Tutor] help with program from learning python the hard way
In-Reply-To: <CANZF_8HOzDxt=Sk5++EjOfn3EbQ7L97ua+HjQxQfHtGohWN04w@mail.gmail.com>
References: <CANZF_8HOzDxt=Sk5++EjOfn3EbQ7L97ua+HjQxQfHtGohWN04w@mail.gmail.com>
Message-ID: <670164913-1326979044-cardhu_decombobulator_blackberry.rim.net-1794457968-@b14.c12.bise7.blackberry>

If I say that sys.argv is a list, does that help you? 

Also, run things from a command prompt for this kind of thing, at least then you can guarantee what args get passed

Bodsda  
Sent from my BlackBerry? wireless device

-----Original Message-----
From: Jason Loeve <jasonloeve at gmail.com>
Sender: tutor-bounces+bodsda=googlemail.com at python.org
Date: Thu, 19 Jan 2012 15:02:41 
To: <tutor at python.org>
Subject: [Tutor] help with program from learning python the hard way

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


From wprins at gmail.com  Thu Jan 19 14:21:50 2012
From: wprins at gmail.com (Walter Prins)
Date: Thu, 19 Jan 2012 13:21:50 +0000
Subject: [Tutor] help with program from learning python the hard way
In-Reply-To: <CANZF_8HOzDxt=Sk5++EjOfn3EbQ7L97ua+HjQxQfHtGohWN04w@mail.gmail.com>
References: <CANZF_8HOzDxt=Sk5++EjOfn3EbQ7L97ua+HjQxQfHtGohWN04w@mail.gmail.com>
Message-ID: <CANLXbfAQaxqPG6UfQ1_nQ=FXk2-+4qpqLy48_88PXmGNZ8GBbw@mail.gmail.com>

Hi Jason,

On 19 January 2012 13:02, Jason Loeve <jasonloeve at gmail.com> wrote:

> good day i seem to be stuck, my code is
>
> from sys import argv
>
> script, user_name = argv
>
> and i get an error ValueError: need more than 1 value to unpack
>

The implication of this message is that the value of "argv" contains only
one value, which would be true if the script was run with no command line
parameters.


>
> http://learnpythonthehardway.org/book/ex14.html
>
> i am using PyCharm 1.5.4 to run
>

I'm not familiar with PyCharm but by default IDE's obviously would not be
passing any command line parameters to programs they run.  Most IDE's have
some way of specifying the command line parameters to pass the script, but
I can't tell you how to do this in PyCharm, so if you insist on running
from PyCharm you'll have to find out how to do that on your own.

I however suggest tha you instead use PyCharm purely as an editor, and
follow the instructions in the Excercise which is to run the script from
the command prompt, with the parameters as shown in the excercise.  Then
you should have not have this problem and you should be able to follow what
the book is doing more closely.

Additionally I suggest you go back to the previous section, Excecise 13 on
"Parameters, Unpacking, Variables" since I get the sense from your question
that you may not have completed this section properly or may have glossed
over it, since if you had successfully completed this then you should not
have had the above problem in the first place.

Cheers

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120119/8e079ae2/attachment.html>

From evert.rol at gmail.com  Thu Jan 19 15:04:26 2012
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 19 Jan 2012 15:04:26 +0100
Subject: [Tutor] Question about install.py
In-Reply-To: <20120118234959.164771p8h7coitqf@webmail.rice.edu>
References: <20120118234959.164771p8h7coitqf@webmail.rice.edu>
Message-ID: <DF595DB6-6FFD-4CE5-844A-3BF4A9B7E72F@gmail.com>

  Hi,

> I'm new to Python and was wondering if someone could answer a question I have.
> Say that I have a python library, arithmetic-0.5, located at /X/arithmetic-0.5
> I'd like to run setup and install it. But I guess since /X/arithmetic-0.5 is not in install.py's default search path, it comes back with an error saying that it cannot find the necessary files.
> Can you please tell me how I can change the search path of install.py? What parameter do I need to modify?

I don't know about install.py. Perhaps you can give a pointer to that (eg, a webpage)?

As far as I my knowledge goes, you install libraries (modules) using setup.py.
In that case, a command like 
$> python setup.py install
should do it. That assumes you're working from the command line. 
Python will automatically install the library in a place where it can find it.
See also http://docs.python.org/install/index.html
It can be easier to use a binary installer though, especially if you're not used to working on command lines.

If you're just trying to install a Python library, it can help if you mention which library you want to install, what you are using for the installation (source code, or installer), which python version and on which OS you are working.
Also, you mention an error, but don't specify it. Python usually comes with a whole backtrace, which you can copy-paste into your email.

Cheers,

  Evert


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


From kellyadrian at hotmail.com  Thu Jan 19 15:32:21 2012
From: kellyadrian at hotmail.com (ADRIAN KELLY)
Date: Thu, 19 Jan 2012 14:32:21 +0000
Subject: [Tutor] appending to a file on a new line
Message-ID: <DUB103-W3212BDC23284D785DA3822A9860@phx.gbl>


Hi everyone,
is there an easy way to write to a file (that already exists with data contained) on a new line.  I understand that the file pointer appends where it left off but how do i write to the next line or even skip a line if possible?
 
User_info=open("C:\\Documents and Settings\\akelly\\Desktop\\details.txt",'a')
User_info.write("\n".join(Details))

 
all the best,  
Adrian  		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120119/2b8d6f81/attachment-0001.html>

From joel.goldstick at gmail.com  Thu Jan 19 15:42:45 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Thu, 19 Jan 2012 09:42:45 -0500
Subject: [Tutor] appending to a file on a new line
In-Reply-To: <DUB103-W3212BDC23284D785DA3822A9860@phx.gbl>
References: <DUB103-W3212BDC23284D785DA3822A9860@phx.gbl>
Message-ID: <CAPM-O+y8qddJgX8HqdC9NM2RVj6JV0-+539Zxe1NJ5tYSPAU-w@mail.gmail.com>

On Thu, Jan 19, 2012 at 9:32 AM, ADRIAN KELLY <kellyadrian at hotmail.com> wrote:
> Hi everyone,
> is there an easy way to write to a file (that already exists with data
> contained) on a new line.? I understand that the file pointer appends where
> it left off but how do i write to the next line or even skip a line if
> possible?
>
> User_info=open("C:\\Documents and
> Settings\\akelly\\Desktop\\details.txt",'a')
> User_info.write("\n".join(Details))
>
>
> all the best,
> Adrian
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
What you wrote looks fine.  When you open a file to append, it does
just that with the write method.

You can learn more here
http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects

When you run your code what happens?


-- 
Joel Goldstick

From d at davea.name  Thu Jan 19 15:43:36 2012
From: d at davea.name (Dave Angel)
Date: Thu, 19 Jan 2012 09:43:36 -0500
Subject: [Tutor] appending to a file on a new line
In-Reply-To: <DUB103-W3212BDC23284D785DA3822A9860@phx.gbl>
References: <DUB103-W3212BDC23284D785DA3822A9860@phx.gbl>
Message-ID: <4F182C18.5000405@davea.name>

On 01/19/2012 09:32 AM, ADRIAN KELLY wrote:
> Hi everyone,
> is there an easy way to write to a file (that already exists with data contained) on a new line.  I understand that the file pointer appends where it left off but how do i write to the next line or even skip a line if possible?
>
> User_info=open("C:\\Documents and Settings\\akelly\\Desktop\\details.txt",'a')
> User_info.write("\n".join(Details))
>
>
> all the best,
> Adrian  		 	   		
>
Presumably this is a text file.  By convention, they end with a newline 
character.  So your data should follow that, and appear on a separate line.

If the file is broken, you can start your data with a \n, just in case.  
Or you could do a separate test, to decide if you need it.

If you want a (an extra) blank line between, simply start your data with 
a \n .

You can also do this as a separate user_info.write("\n")  of course.



-- 

DaveA


From kellyadrian at hotmail.com  Thu Jan 19 16:04:40 2012
From: kellyadrian at hotmail.com (ADRIAN KELLY)
Date: Thu, 19 Jan 2012 15:04:40 +0000
Subject: [Tutor] appending to a file on a new line
In-Reply-To: <CAPM-O+y8qddJgX8HqdC9NM2RVj6JV0-+539Zxe1NJ5tYSPAU-w@mail.gmail.com>
References: <DUB103-W3212BDC23284D785DA3822A9860@phx.gbl>,
	<CAPM-O+y8qddJgX8HqdC9NM2RVj6JV0-+539Zxe1NJ5tYSPAU-w@mail.gmail.com>
Message-ID: <DUB103-W385FBBEB4408C4DF8C31ACA9860@phx.gbl>


guys,
its a text file i am writing to and when i write the first time its fine, i get 3 lines of input collected from a user and written to my text file, however if i run the program again the next 3 lines begin at the end of the previous users details.  It works fine but starts from where the pointer left off.  i dont know how to solve this.  where do i put the '\n'?  to be honest the .join i dont understand but otherwise it prints as a list e.g. ('name','age','etc')
Adrian 
 

> Date: Thu, 19 Jan 2012 09:42:45 -0500
> Subject: Re: [Tutor] appending to a file on a new line
> From: joel.goldstick at gmail.com
> To: kellyadrian at hotmail.com
> CC: tutor at python.org
> 
> On Thu, Jan 19, 2012 at 9:32 AM, ADRIAN KELLY <kellyadrian at hotmail.com> wrote:
> > Hi everyone,
> > is there an easy way to write to a file (that already exists with data
> > contained) on a new line.  I understand that the file pointer appends where
> > it left off but how do i write to the next line or even skip a line if
> > possible?
> >
> > User_info=open("C:\\Documents and
> > Settings\\akelly\\Desktop\\details.txt",'a')
> > User_info.write("\n".join(Details))
> >
> >
> > all the best,
> > Adrian
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> >
> What you wrote looks fine. When you open a file to append, it does
> just that with the write method.
> 
> You can learn more here
> http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects
> 
> When you run your code what happens?
> 
> 
> -- 
> Joel Goldstick
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120119/d3dc75c1/attachment.html>

From d at davea.name  Thu Jan 19 16:12:16 2012
From: d at davea.name (Dave Angel)
Date: Thu, 19 Jan 2012 10:12:16 -0500
Subject: [Tutor] appending to a file on a new line
In-Reply-To: <DUB103-W385FBBEB4408C4DF8C31ACA9860@phx.gbl>
References: <DUB103-W3212BDC23284D785DA3822A9860@phx.gbl>,
	<CAPM-O+y8qddJgX8HqdC9NM2RVj6JV0-+539Zxe1NJ5tYSPAU-w@mail.gmail.com>
	<DUB103-W385FBBEB4408C4DF8C31ACA9860@phx.gbl>
Message-ID: <4F1832D0.406@davea.name>

On 01/19/2012 10:04 AM, ADRIAN KELLY wrote:
> guys,
> its a text file i am writing to and when i write the first time its fine, i get 3 lines of input collected from a user and written to my text file, however if i run the program again the next 3 lines begin at the end of the previous users details.  It works fine but starts from where the pointer left off.  i dont know how to solve this.  where do i put the '\n'?  to be honest the .join i dont understand but otherwise it prints as a list e.g. ('name','age','etc')
> Adrian
>
>

You top-posted.  Please put your response *after* what you're quoting.

Anyway, since you're the one writing the original file, the problem is, 
as I said, the file is broken.  You don't write a trailing newline.  So 
the simplest fix is to add another write() call.

User_info.write("\n".join(Details))
User_info.write("\n")

The join command puts the specified text *between* the list elements, 
but not after the last one.

-- 

DaveA


From tony.pelletier at gmail.com  Thu Jan 19 16:24:40 2012
From: tony.pelletier at gmail.com (Tony Pelletier)
Date: Thu, 19 Jan 2012 10:24:40 -0500
Subject: [Tutor] Facebook apps with python
In-Reply-To: <SNT130-W63F504B90A6271F0CD46AEA4810@phx.gbl>
References: <SNT130-W63F504B90A6271F0CD46AEA4810@phx.gbl>
Message-ID: <CAOjO5CP5VRmWfOfyXE_ZQLmo9hxhZsi15SyqAfnzEaEQo-tT6Q@mail.gmail.com>

On Wed, Jan 18, 2012 at 8:34 AM, karthik s <suryak at live.com> wrote:
> Well, my question is simple..
> How do I create facebook apps with python. I have couple of interesting/
> funky programs and want to make them as apps.
> So,
> 1. What all things I should know for writing facebook apps.
> 2. I read that we should first upload our app to 'google app engine' and
> need do link it to facebook.. Is that right?
> 3. Actually, I am not aware of Network/ Web programming.. can I be able to
> do that?
> 4. Please do mention a couple of books (ebooks) from which I can learn..
> That will help me.



I don't know if this will help, but the Facebook Graph API allows you do
neat things.

https://developers.facebook.com/docs/reference/api/


Here's something small I wrote a little while ago that just grabs all your
friends profile photos and saves them with their name as the filename.  Not
necessarily anything useful, but a small example of what you can do with
it.

#!/usr/bin/env python

import os
import httplib
import json
from urllib import urlretrieve


server = 'graph.facebook.com'
myID = 'username'
accessToken = 'this is the token'
URL = "/usernam/friends?access_token=" + accessToken

def getfriends():
    conn = httplib.HTTPSConnection(server)
    conn.request("GET", URL)
    response = conn.getresponse()
    data = response.read()
    list = json.loads(data)['data']
    IDs = [(friends['id'], friends['name']) for friends in list]
    return IDs


def getphotos():
    if not os.path.exists("photos"):
        os.makedirs("photos")

    for id, name in getfriends():
        url = "https://graph.facebook.com/" + id + "/picture"
        filename = os.path.join("photos", "%s.jpg" % (name))
        urlretrieve(url, filename)

def main():
    getphotos()

if __name__ == '__main__':
    main()






>
> _______________________________________________
> 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/20120119/37c6d902/attachment-0001.html>

From ilhs_hs at yahoo.com  Thu Jan 19 19:09:27 2012
From: ilhs_hs at yahoo.com (Hs Hs)
Date: Thu, 19 Jan 2012 10:09:27 -0800 (PST)
Subject: [Tutor] finding a polymer of letters in a string
Message-ID: <1326996567.17300.YahooMailNeo@web111205.mail.gq1.yahoo.com>

Hi:?
I am writing to see if I could any help.
I am trying to find if a mutation in gene falls in a polymer region of DNA. To explain in simplistic terms, 


Given a piece of DNA string, with following characters, I know where mutation happens.? Happens at T (in quotes with spaces.) 3 As before T and 4 As after T are removed in a disease. 


Given following sequence, I should be able to find if this T is in a polymer region. such as 'AAA' T 'AAAA. 


AAATAGCAGAAA 'T' AAAAGAAAAGATTGGAACTAGGTCAG



I am not sure if there are any methods in python to find these.? Do you think a script has to be written with more logic involving some known algorithms. 


Please advise. 


thanks
Hs.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120119/8cb38a4b/attachment.html>

From hgfernan at gmail.com  Thu Jan 19 19:39:59 2012
From: hgfernan at gmail.com (Hilton Fernandes)
Date: Thu, 19 Jan 2012 16:39:59 -0200
Subject: [Tutor] finding a polymer of letters in a string
In-Reply-To: <1326996567.17300.YahooMailNeo@web111205.mail.gq1.yahoo.com>
References: <1326996567.17300.YahooMailNeo@web111205.mail.gq1.yahoo.com>
Message-ID: <CAA7w9gmtKQJDKnZha5tvExYim3bqVscy-qtO83r6BcjBPZnf_Q@mail.gmail.com>

Hi !

Have you considered regular expressions in Python ?

Please take a look at "Regular Expression HOWTO", at
http://docs.python.org/howto/regex.html

All the best,
Hilton

On Thu, Jan 19, 2012 at 4:09 PM, Hs Hs <ilhs_hs at yahoo.com> wrote:

> Hi:
> I am writing to see if I could any help.
> I am trying to find if a mutation in gene falls in a polymer region of
> DNA. To explain in simplistic terms,
>
> Given a piece of DNA string, with following characters, I know where
> mutation happens.  Happens at T (in quotes with spaces.) 3 As before T and
> 4 As after T are removed in a disease.
>
> Given following sequence, I should be able to find if this T is in a
> polymer region. such as 'AAA' T 'AAAA.
>
> AAATAGCAGAAA 'T' AAAAGAAAAGATTGGAACTAGGTCAG
>
>
>
> I am not sure if there are any methods in python to find these.  Do you
> think a script has to be written with more logic involving some known
> algorithms.
>
> Please advise.
>
> thanks
> Hs.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
(11)8131-5213
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120119/453b1e6f/attachment.html>

From ilhs_hs at yahoo.com  Thu Jan 19 19:44:36 2012
From: ilhs_hs at yahoo.com (Hs Hs)
Date: Thu, 19 Jan 2012 10:44:36 -0800 (PST)
Subject: [Tutor] finding a polymer of letters in a string
In-Reply-To: <CAA7w9gmtKQJDKnZha5tvExYim3bqVscy-qtO83r6BcjBPZnf_Q@mail.gmail.com>
References: <1326996567.17300.YahooMailNeo@web111205.mail.gq1.yahoo.com>
	<CAA7w9gmtKQJDKnZha5tvExYim3bqVscy-qtO83r6BcjBPZnf_Q@mail.gmail.com>
Message-ID: <1326998676.5987.YahooMailNeo@web111214.mail.gq1.yahoo.com>

Hi Hilton. Thanks for your suggestion. 



I saw re module. I should have explain a little bit in my message that patter of polymer is not constant. There could be variety of combinations given A, T G and C. 

it could be AAATAAA, ATATATAT, or GTAGTAGTA or GGGACCCGAAAT etc.


so I do not know what that pattern would be when I read in a string. I do not know if regex could solve my kind of problem too. 


Thanks
Hs.





________________________________
 From: Hilton Fernandes <hgfernan at gmail.com>
To: "tutor at python.org" <tutor at python.org> 
Cc: Hs Hs <ilhs_hs at yahoo.com> 
Sent: Thursday, January 19, 2012 1:39 PM
Subject: Re: [Tutor] finding a polymer of letters in a string
 

Hi !?

Have you considered regular expressions in Python ??

Please take a look at "Regular Expression HOWTO", at?
http://docs.python.org/howto/regex.html

All the best,?
Hilton?


On Thu, Jan 19, 2012 at 4:09 PM, Hs Hs <ilhs_hs at yahoo.com> wrote:

Hi:?
>I am writing to see if I could any help.
>I am trying to find if a mutation in gene falls in a polymer region of DNA. To explain in simplistic terms, 
>
>
>
>Given a piece of DNA string, with following characters, I know where mutation happens.? Happens at T (in quotes with spaces.) 3 As before T and 4 As after T are removed in a disease. 
>
>
>
>Given following sequence, I should be able to find if this T is in a polymer region. such as 'AAA' T 'AAAA. 
>
>
>
>AAATAGCAGAAA 'T' AAAAGAAAAGATTGGAACTAGGTCAG
>
>
>
>
>
>
>I am not sure if there are any methods in python to find these.? Do you think a script has to be written with more logic involving some known algorithms. 
>
>
>
>Please advise. 
>
>
>
>thanksHs.
>
>_______________________________________________
>Tutor maillist ?- ?Tutor at python.org
>To unsubscribe or change subscription options:
>http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
(11)8131-5213
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120119/9510cc0c/attachment.html>

From malaclypse2 at gmail.com  Thu Jan 19 21:10:26 2012
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Thu, 19 Jan 2012 15:10:26 -0500
Subject: [Tutor] finding a polymer of letters in a string
In-Reply-To: <1326998676.5987.YahooMailNeo@web111214.mail.gq1.yahoo.com>
References: <1326996567.17300.YahooMailNeo@web111205.mail.gq1.yahoo.com>
	<CAA7w9gmtKQJDKnZha5tvExYim3bqVscy-qtO83r6BcjBPZnf_Q@mail.gmail.com>
	<1326998676.5987.YahooMailNeo@web111214.mail.gq1.yahoo.com>
Message-ID: <CADwdpyanif-nuJUusyWW=kvi-J4P=T4wJtprXckx_UC-k4yqTA@mail.gmail.com>

On Thu, Jan 19, 2012 at 1:44 PM, Hs Hs <ilhs_hs at yahoo.com> wrote:

> so I do not know what that pattern would be when I read in a string. I do
> not know if regex could solve my kind of problem too.
>

Ignore the python portion of the problem for now.

Imagine someone handed you a piece of paper with the letters
"AAATAGCAGAAATAAAAGAAAAGATTGGAACTAGGTCAG" written on it, and asked you to
circle the section that you're trying to identify.  How would you do it,
without using a computer?  How do you figure out where there was a
mutation, and then how do you discover if that location is in a polymer
region?

If you can describe that process to us, maybe we can help you turn that
into a python program.

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

From delegbede at dudupay.com  Thu Jan 19 22:09:14 2012
From: delegbede at dudupay.com (delegbede at dudupay.com)
Date: Thu, 19 Jan 2012 21:09:14 +0000
Subject: [Tutor] finding a polymer of letters in a string
In-Reply-To: <1326996567.17300.YahooMailNeo@web111205.mail.gq1.yahoo.com>
References: <1326996567.17300.YahooMailNeo@web111205.mail.gq1.yahoo.com>
Message-ID: <1781595139-1327007355-cardhu_decombobulator_blackberry.rim.net-1702467561-@b13.c12.bise7.blackberry>

Hi,

The explanation you have given isn't good enough to get us anywhere. 

What are the possible patterns?

Do you have a fixed number of As you're looking out for?

What defines a polymer region?

The different DNA samples, how are they separated? With commas, new lines etc? 

You can do a line by line explanation and we could get some people in here to help you get python codes to achieve what you just explained. 

Regards. 
Sent from my BlackBerry wireless device from MTN

-----Original Message-----
From: Hs Hs <ilhs_hs at yahoo.com>
Sender: tutor-bounces+delegbede=dudupay.com at python.org
Date: Thu, 19 Jan 2012 10:09:27 
To: tutor at python.org<tutor at python.org>
Reply-To: Hs Hs <ilhs_hs at yahoo.com>
Subject: [Tutor] finding a polymer of letters in a string

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



From hgfernan at gmail.com  Thu Jan 19 23:05:13 2012
From: hgfernan at gmail.com (Hilton Fernandes)
Date: Thu, 19 Jan 2012 20:05:13 -0200
Subject: [Tutor] Detail your problem,
 privately (was Re:  finding a polymer of letters in a string)
Message-ID: <CAA7w9gnX7PiTMRFrRn4X5kV_3+oVfp4wpBdqFpCyNoBTaofbww@mail.gmail.com>

Hi, Hs !

I believe that in this list there are people that know a lot about either
regular expressions in Python, or about DNA strings.

They will be able to give you qualified help about what you are asking,
since you provide them enough data.

In any case, you can write to me privately  if you'd like to teach this
General Purpose programmer about DNA strings, i'd happy to learn about
them, as well to think about regular expressions in this context.

Maybe the two of us can think about an interesting solution for your
problem.

All the best,
Hilton

On Thu, Jan 19, 2012 at 4:44 PM, Hs Hs <ilhs_hs at yahoo.com> wrote:

> Hi Hilton. Thanks for your suggestion.
>
>
> I saw re module. I should have explain a little bit in my message that
> patter of polymer is not constant. There could be variety of combinations
> given A, T G and C.
> it could be AAATAAA, ATATATAT, or GTAGTAGTA or GGGACCCGAAAT etc.
>
> so I do not know what that pattern would be when I read in a string. I do
> not know if regex could solve my kind of problem too.
>
> Thanks
> Hs.
>
>
>
>   ------------------------------
> *From:* Hilton Fernandes <hgfernan at gmail.com>
> *To:* "tutor at python.org" <tutor at python.org>
> *Cc:* Hs Hs <ilhs_hs at yahoo.com>
> *Sent:* Thursday, January 19, 2012 1:39 PM
> *Subject:* Re: [Tutor] finding a polymer of letters in a string
>
> Hi !
>
> Have you considered regular expressions in Python ?
>
> Please take a look at "Regular Expression HOWTO", at
> http://docs.python.org/howto/regex.html
>
> All the best,
> Hilton
>
> On Thu, Jan 19, 2012 at 4:09 PM, Hs Hs <ilhs_hs at yahoo.com> wrote:
>
> Hi:
> I am writing to see if I could any help.
> I am trying to find if a mutation in gene falls in a polymer region of
> DNA. To explain in simplistic terms,
>
> Given a piece of DNA string, with following characters, I know where
> mutation happens.  Happens at T (in quotes with spaces.) 3 As before T and
> 4 As after T are removed in a disease.
>
> Given following sequence, I should be able to find if this T is in a
> polymer region. such as 'AAA' T 'AAAA.
>
> AAATAGCAGAAA 'T' AAAAGAAAAGATTGGAACTAGGTCAG
>
>
>
> I am not sure if there are any methods in python to find these.  Do you
> think a script has to be written with more logic involving some known
> algorithms.
>
> Please advise.
>
> thanks
> Hs.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
>
> --
> (11)8131-5213
>
>
>
>
>


-- 
(11)8131-5213
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120119/f48f0a56/attachment.html>

From oberoc at gmail.com  Fri Jan 20 19:34:23 2012
From: oberoc at gmail.com (Tino Dai)
Date: Fri, 20 Jan 2012 13:34:23 -0500
Subject: [Tutor] Namespace question
Message-ID: <CAOu0yXZEhUbroDyL2Y7u2fTLScqengfvzH=h==KpEdGc8=MWeA@mail.gmail.com>

Hi everybody,

     Got a namespace question framed inside a Django project (but I still
think it's pertinent to Python). We moved and broke settings.py four
different files in a separate directory called settings. So instead of
doing a

>>> import settings
>>> settings.whatever

We are having to do:

>>> import settings
>>> settings.settings.whatever

This is inconvenient and probably will break stuff especially with django
framework code. Is there a way to play with the namespacing to have python
have the former behavior rather than the latter behavior?

Thanks,
Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120120/cbc1541e/attachment.html>

From d at davea.name  Fri Jan 20 19:51:47 2012
From: d at davea.name (Dave Angel)
Date: Fri, 20 Jan 2012 13:51:47 -0500
Subject: [Tutor] Namespace question
In-Reply-To: <CAOu0yXZEhUbroDyL2Y7u2fTLScqengfvzH=h==KpEdGc8=MWeA@mail.gmail.com>
References: <CAOu0yXZEhUbroDyL2Y7u2fTLScqengfvzH=h==KpEdGc8=MWeA@mail.gmail.com>
Message-ID: <4F19B7C3.9000305@davea.name>

On 01/20/2012 01:34 PM, Tino Dai wrote:
> Hi everybody,
>
>       Got a namespace question framed inside a Django project (but I still
> think it's pertinent to Python). We moved and broke settings.py four
> different files in a separate directory called settings. So instead of
> doing a
>
>>>> import settings
>>>> settings.whatever
> We are having to do:
>
>>>> import settings
>>>> settings.settings.whatever
I would try to never have the same name used at two different scope 
levels.  if you have a module called settings, don't put it in a package 
called settings.  (Similarly, the familiar capitalization convention - 
name the file with lowercase, and a class within the file capitalized.)
> This is inconvenient and probably will break stuff especially with django
> framework code. Is there a way to play with the namespacing to have python
> have the former behavior rather than the latter behavior?
>
> Thanks,
> Tino
I haven't done it myself, but you can have package initialization code 
in  settings/__init__.py   that code can customize what the user sees 
when importing your package.

It's not clear to me what you're willing to change and what you cannot.



-- 

DaveA


From emile at fenx.com  Fri Jan 20 20:42:30 2012
From: emile at fenx.com (Emile van Sebille)
Date: Fri, 20 Jan 2012 11:42:30 -0800
Subject: [Tutor] Namespace question
In-Reply-To: <CAOu0yXZEhUbroDyL2Y7u2fTLScqengfvzH=h==KpEdGc8=MWeA@mail.gmail.com>
References: <CAOu0yXZEhUbroDyL2Y7u2fTLScqengfvzH=h==KpEdGc8=MWeA@mail.gmail.com>
Message-ID: <jfcg3a$7om$1@dough.gmane.org>

On 1/20/2012 10:34 AM Tino Dai said...
> Hi everybody,
>
>       Got a namespace question framed inside a Django project (but I
> still think it's pertinent to Python). We moved and broke settings.py
> four different files in a separate directory called settings. So instead
> of doing a
>
>  >>> import settings
>  >>> settings.whatever
>
> We are having to do:
>
>  >>> import settings
>  >>> settings.settings.whatever


You could....

from settings import settings

... which then allows access as

settings.whatever


HTH,

Emile


>
> This is inconvenient and probably will break stuff especially with
> django framework code. Is there a way to play with the namespacing to
> have python have the former behavior rather than the latter behavior?
>
> Thanks,
> Tino
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



From rhettnaxel at gmail.com  Fri Jan 20 22:56:14 2012
From: rhettnaxel at gmail.com (Alexander)
Date: Fri, 20 Jan 2012 16:56:14 -0500
Subject: [Tutor] Namespace question
In-Reply-To: <jfcg3a$7om$1@dough.gmane.org>
References: <CAOu0yXZEhUbroDyL2Y7u2fTLScqengfvzH=h==KpEdGc8=MWeA@mail.gmail.com>
	<jfcg3a$7om$1@dough.gmane.org>
Message-ID: <CANS6qmBOqyAeeHK51o3FdBaBH4O=Yd-NqKCRRVr0PgvTK7Y6XA@mail.gmail.com>

On Fri, Jan 20, 2012 at 2:42 PM, Emile van Sebille <emile at fenx.com> wrote:

> On 1/20/2012 10:34 AM Tino Dai said...
>
>  Hi everybody,
>>
>>      Got a namespace question framed inside a Django project (but I
>> still think it's pertinent to Python). We moved and broke settings.py
>> four different files in a separate directory called settings. So instead
>> of doing a
>>
>>  >>> import settings
>>  >>> settings.whatever
>>
>> We are having to do:
>>
>>  >>> import settings
>>  >>> settings.settings.whatever
>>
>
>
> You could....
>
> from settings import settings
>
> ... which then allows access as
>
> settings.whatever
>
>
> HTH,
>
> Emile
>
>
>
>> This is inconvenient and probably will break stuff especially with
>> django framework code. Is there a way to play with the namespacing to
>> have python have the former behavior rather than the latter behavior?
>>
>> Thanks,
>> Tino
>>
>>
>>
>> ______________________________**_________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/**mailman/listinfo/tutor<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<http://mail.python.org/mailman/listinfo/tutor>
>

Yes I think you could also:

>>> import settings as settings
or
>>> import settings as s

( or whatever )


-- 
Alexander
7D9C597B
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120120/beb64c1b/attachment.html>

From eire1130 at gmail.com  Sat Jan 21 00:31:52 2012
From: eire1130 at gmail.com (eire1130 at gmail.com)
Date: Fri, 20 Jan 2012 23:31:52 +0000
Subject: [Tutor] Fw:  Namespace question
Message-ID: <1136417277-1327102315-cardhu_decombobulator_blackberry.rim.net-1783123342-@b5.c28.bise6.blackberry>


Sent from my Verizon Wireless BlackBerry

-----Original Message-----
From: eire1130 at gmail.com
Date: Fri, 20 Jan 2012 23:26:05 
To: Tino Dai<oberoc at gmail.com>
Reply-To: eire1130 at gmail.com
Subject: Re: [Tutor] Namespace question

Is there any reason you broke up settings? My understanding is each app gets its own settings file, but then I don't have a project with more than one app residing in it.

Multiple apps is the only reason I can see to break it up. I think you should try this same question on django-users (I follow that list as well)

At any rate, have you tried from settings import settings like emile suggested, your worries notwithstanding?





Sent from my Verizon Wireless BlackBerry

-----Original Message-----
From: Tino Dai <oberoc at gmail.com>
Sender: tutor-bounces+eire1130=gmail.com at python.org
Date: Fri, 20 Jan 2012 13:34:23 
To: *tutor python<tutor at python.org>
Cc: <rlarson at loc.gov>
Subject: [Tutor] Namespace question

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


From shreeshbhat90 at gmail.com  Sat Jan 21 14:10:28 2012
From: shreeshbhat90 at gmail.com (Shreesh bhat)
Date: Sat, 21 Jan 2012 18:40:28 +0530
Subject: [Tutor] OverFlow Error
Message-ID: <CA+XJMJ5mVBWqVbTwhNwO4_5+XpdD_PnV2c66M1+vm6W+a7TySg@mail.gmail.com>

How to correct this error?

* OverflowError: Python int too large to convert to C long*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120121/f7b86624/attachment.html>

From alan.gauld at btinternet.com  Sat Jan 21 14:57:20 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 21 Jan 2012 13:57:20 +0000
Subject: [Tutor] OverFlow Error
In-Reply-To: <CA+XJMJ5mVBWqVbTwhNwO4_5+XpdD_PnV2c66M1+vm6W+a7TySg@mail.gmail.com>
References: <CA+XJMJ5mVBWqVbTwhNwO4_5+XpdD_PnV2c66M1+vm6W+a7TySg@mail.gmail.com>
Message-ID: <jfeg80$dh5$1@dough.gmane.org>

On 21/01/12 13:10, Shreesh bhat wrote:
> How to correct this error?
>
> * OverflowError: Python int too large to convert to C long*


Could we have some context?

What version of Python? What OS?
What does your code look like?
Can we see the full error trace please?

Otherwise, based only on what you posted, the only advice
I can give you is to use a smaller int!


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


From geonyoro at gmail.com  Sat Jan 21 15:58:17 2012
From: geonyoro at gmail.com (George Nyoro)
Date: Sat, 21 Jan 2012 17:58:17 +0300
Subject: [Tutor] Tutor Digest, Vol 95, Issue 53
In-Reply-To: <mailman.19.1327057202.23000.tutor@python.org>
References: <mailman.19.1327057202.23000.tutor@python.org>
Message-ID: <CAM71YVE43XUXv5FmOvaXhL3Pv=-jvrvuOXEhU-fQky08oEHXCA@mail.gmail.com>

Hey guys,
I've been making an application and have made a delete method where the
user can delete the instance of that application. e.g. if I have a table
object, I need to be able to delete that instance from within the class and
then it becomes accessible.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120121/d6796ae7/attachment.html>

From steve at pearwood.info  Sat Jan 21 16:07:45 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 22 Jan 2012 02:07:45 +1100
Subject: [Tutor] Tutor Digest, Vol 95, Issue 53
In-Reply-To: <CAM71YVE43XUXv5FmOvaXhL3Pv=-jvrvuOXEhU-fQky08oEHXCA@mail.gmail.com>
References: <mailman.19.1327057202.23000.tutor@python.org>
	<CAM71YVE43XUXv5FmOvaXhL3Pv=-jvrvuOXEhU-fQky08oEHXCA@mail.gmail.com>
Message-ID: <4F1AD4C1.3040406@pearwood.info>

George Nyoro wrote:
> Hey guys,
> I've been making an application and have made a delete method where the
> user can delete the instance of that application. e.g. if I have a table
> object, I need to be able to delete that instance from within the class and
> then it becomes accessible.

Did you want to ask a question, or are you just sharing?


-- 
Steven


From d at davea.name  Sat Jan 21 16:27:34 2012
From: d at davea.name (Dave Angel)
Date: Sat, 21 Jan 2012 10:27:34 -0500
Subject: [Tutor] delete an object from method (was Tutor Digest)
In-Reply-To: <CAM71YVE43XUXv5FmOvaXhL3Pv=-jvrvuOXEhU-fQky08oEHXCA@mail.gmail.com>
References: <mailman.19.1327057202.23000.tutor@python.org>
	<CAM71YVE43XUXv5FmOvaXhL3Pv=-jvrvuOXEhU-fQky08oEHXCA@mail.gmail.com>
Message-ID: <4F1AD966.2070702@davea.name>

On 01/21/2012 09:58 AM, George Nyoro wrote:
> Hey guys,
> I've been making an application and have made a delete method where the
> user can delete the instance of that application. e.g. if I have a table
> object, I need to be able to delete that instance from within the class and
> then it becomes accessible.
>

If you're going to misuse so many terms in one query, you'll need to 
supply some code, and tell us in what way it doesn't serve your needs.

In the meantime,

1) Post a query by addressing it to "tutor at python.org," not by replying 
to  a digest message.  And if you must reply to a digest message, at 
least change the subject.  Thanks, though for deleting the digest content.

2) How do you expect to delete the instance of the application?  It's a 
funny term, but the only meaning I can come up with is you want to kill 
the application's process.

3) What's a table object?  If table is the name of your class, it really 
ought to be uppercase.

4) "from within the class" --  I'm guessing you mean from within a 
method of the class.

5) "then it becomes accessible" -- perhaps you mean inaccessible.

6) Please tell us the version of Python you're using and the operating 
system you're running on.



-- 

DaveA


From nikunjbadjatya at gmail.com  Sat Jan 21 19:47:39 2012
From: nikunjbadjatya at gmail.com (Nikunj Badjatya)
Date: Sun, 22 Jan 2012 00:17:39 +0530
Subject: [Tutor] checking return status of 'ping' in windows
In-Reply-To: <CAOwQg9tW+-M1thVSA_C30axYE8sJ_0Go_PNg3xSvj8jiNcZwaA@mail.gmail.com>
References: <CAOwQg9tW+-M1thVSA_C30axYE8sJ_0Go_PNg3xSvj8jiNcZwaA@mail.gmail.com>
Message-ID: <CAOwQg9u6esoRAvUipX+ZshiFcbc_2gvQmYd8dZFcgQu6617NWA@mail.gmail.com>

Hi All,

I am using the following snippet to check the availability of an IP
address. If that IP addr is found free than it can be used later on for
further operations.
Python ver 3.2
Windows OS

{{{
pingret = subprocess.Popen('ping {0}'.format(IPaddr),
shell=True,universal_newlines=True, \
                    stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
status = pingret.wait()
if status == 0:
    print("WARN  The IP given in the input is not free")
.....
.....
}}}

Normal ping operation on windows cmd prompt can give 3 outputs.
1) "destination host unreachable
2) "request timed out"
3) "Reply from 192.168.1.1: bytes=32 time=3ms TTL=64"

Now,
I was expecting the "status" in above snippet to hold '0' only in case of
no. 3)
But even when we have case 1), 'status' is holding '0'.
i.e. The exit status of ping is 0, even when destination host is
unreachable.!

How do I make my snippet to work as desired. i.e even if destination host
is unreachable, 'status' should hold '1'  and hold '0' only when it gets
reply from that ip address.??


Thanks,

Nikunj


--
*7*Switch off as you go |*q*Recycle always | P Save Paper - Save Trees | Go
Green
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120122/0250ad3d/attachment.html>

From hugo.yoshi at gmail.com  Sat Jan 21 23:53:42 2012
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sat, 21 Jan 2012 23:53:42 +0100
Subject: [Tutor] checking return status of 'ping' in windows
In-Reply-To: <CAOwQg9u6esoRAvUipX+ZshiFcbc_2gvQmYd8dZFcgQu6617NWA@mail.gmail.com>
References: <CAOwQg9tW+-M1thVSA_C30axYE8sJ_0Go_PNg3xSvj8jiNcZwaA@mail.gmail.com>
	<CAOwQg9u6esoRAvUipX+ZshiFcbc_2gvQmYd8dZFcgQu6617NWA@mail.gmail.com>
Message-ID: <CAJmBOfni1jcSEwz65g76sXeuuM9oXepcZMsTXXrXECcoJdbkUQ@mail.gmail.com>

On Sat, Jan 21, 2012 at 7:47 PM, Nikunj Badjatya
<nikunjbadjatya at gmail.com> wrote:
> Hi All,
>
> I am using the following snippet to check the availability of an IP address.
> If that IP addr is found free than it can be used later on for further
> operations.
> Python ver 3.2
> Windows OS
>
> {{{
> pingret = subprocess.Popen('ping {0}'.format(IPaddr),
> shell=True,universal_newlines=True, \
> ? ? ? ? ? ? ? ? ? ? stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
> status = pingret.wait()
> if status == 0:
> ? ? print("WARN ?The IP given in the input is not free")
> .....
> .....
> }}}
>
> Normal ping operation on windows cmd prompt can give 3 outputs.
> 1) "destination host unreachable
> 2) "request timed out"
> 3) "Reply from 192.168.1.1: bytes=32 time=3ms TTL=64"
>
> Now,
> I was expecting the "status" in above snippet to hold '0' only in case of
> no. 3)
> But even when we have case 1), 'status' is holding '0'.
> i.e. The exit status of ping is 0, even when destination host is
> unreachable.!
>

This appears to be windows specific. Linux ping will return an exit
code of 1 if either zero responses are received or a packetcount and
deadline are specified and not met. I'm not sure why it doesn't work
that way on windows, but testing a bit for myself it seems to be the
platform's fault and not python's, since calling EXIT 1 will correctly
return a status code of 1.

> How do I make my snippet to work as desired. i.e even if destination host is
> unreachable, 'status' should hold '1' ?and hold '0' only when it gets reply
> from that ip address.??
>

rather than using the wait() call, use Popen.communicate() which
returns the output of the program, and check that directly for your
three cases.

HTH,
Hugo

From alan.gauld at btinternet.com  Sun Jan 22 00:20:13 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 21 Jan 2012 23:20:13 +0000
Subject: [Tutor] checking return status of 'ping' in windows
In-Reply-To: <CAOwQg9u6esoRAvUipX+ZshiFcbc_2gvQmYd8dZFcgQu6617NWA@mail.gmail.com>
References: <CAOwQg9tW+-M1thVSA_C30axYE8sJ_0Go_PNg3xSvj8jiNcZwaA@mail.gmail.com>
	<CAOwQg9u6esoRAvUipX+ZshiFcbc_2gvQmYd8dZFcgQu6617NWA@mail.gmail.com>
Message-ID: <jffh7d$osb$1@dough.gmane.org>

On 21/01/12 18:47, Nikunj Badjatya wrote:

> Normal ping operation on windows cmd prompt can give 3 outputs.
> 1) "destination host unreachable
> 2) "request timed out"
> 3) "Reply from 192.168.1.1 <http://192.168.1.1>: bytes=32 time=3ms TTL=64"
>
> Now,
> I was expecting the "status" in above snippet to hold '0' only in case
> of no. 3)
> But even when we have case 1), 'status' is holding '0'.
> i.e. The exit status of ping is 0, even when destination host is
> unreachable.!

The exit status tells you whether the program worked ok,
which could be interpreted, as it apparemtly is in the
case of Windows ping not to include whether it found
a host. If the ping program executed with no errors
you will get no errors. Its kind of arbitrary how you
define an 'error'...

So it seems like you will need to examine the actual output
of ping by looking at the content of stdout/err.

The good news is that this is fairly easy in the case of your ping 
because you can tell from the first word.

def pingStatus(resultString):
     key = resultString.split()[0]
     if key.lower().startswith('rep'): return 0
     elif key.lower().startswith('req'): return 1
     elif key.lower().startswith('des'): return 2
     else: return -1

should give you something like what you were looking for.
Reading Popen stdout I leave as an exercise for the reader :-)

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


From shreeshbhat90 at gmail.com  Sun Jan 22 07:11:22 2012
From: shreeshbhat90 at gmail.com (Shreesh bhat)
Date: Sun, 22 Jan 2012 11:41:22 +0530
Subject: [Tutor] Tutor Digest, Vol 95, Issue 55
In-Reply-To: <mailman.26988.1327186455.27777.tutor@python.org>
References: <mailman.26988.1327186455.27777.tutor@python.org>
Message-ID: <CA+XJMJ7__MSbr-669+D1meWacJdF+HJ8O0vpH7mHRgM+NQXC=g@mail.gmail.com>

*Lucky Numbers*
A number is called lucky if the sum of its digits, as well as the sum of
the squares of its digits is a prime number. How many numbers between A and
B are lucky?
Input:
The first line contains the number of test cases T. Each of the next T
lines contains two integers, A and B.
Output:
Output T lines, one for each case containing the required answer for the
corresponding case.

Constraints:
1 <= T <= 10000
1 <= A <= B <= 10^18
Sample Input:
2
1 20
120 130
Sample Output:
4
1
Explanation:
For the first case, the lucky numbers are 11, 12, 14, 16.
For the second case, the only lucky number is 120.

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
My solution:

def isprime(n):
  n=abs(int(n))
  if n<2:
    return False
  if n==2:
    return True
  if not n & 1:
    return False
  for x in range(3,int(n**0.5)+1,2):
    if n % x == 0:
      return False
  return True

def islucky(n):
  sum1=0
  sum2=0
  while n!=0:
    r=n%10
    sum1+=r
    sum2+=r*r
    n=n/10
  if isprime(sum1) & isprime(sum2):
    return True
  return False

number=raw_input()


for i in range(int(number)):
    inp=raw_input()
    a=inp.split()
    startnum=int(a[0])
    endnum=int(a[1])
    li=map(islucky,xrange(startnum, endnum))
    count=0
    for j in li:
        if j:
            count+=1
    print count
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Traceback (most recent call last): File
"/run-1327085301-1965755690/solution.py",
 line 35, in li=map(islucky,xrange(startnum, endnum))
OverflowError: Python int too large to convert to C long

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
It shows this error for very large numbers or slows down with large numbers.
I m using Ubuntu 32-bit.

On Sun, Jan 22, 2012 at 4:24 AM, <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. OverFlow Error (Shreesh bhat)
>   2. Re: OverFlow Error (Alan Gauld)
>   3. Re: Tutor Digest, Vol 95, Issue 53 (George Nyoro)
>   4. Re: Tutor Digest, Vol 95, Issue 53 (Steven D'Aprano)
>   5. Re: delete an object from method (was Tutor Digest) (Dave Angel)
>   6. checking return status of 'ping' in windows (Nikunj Badjatya)
>   7. Re: checking return status of 'ping' in windows (Hugo Arts)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Sat, 21 Jan 2012 18:40:28 +0530
> From: Shreesh bhat <shreeshbhat90 at gmail.com>
> To: tutor at python.org
> Subject: [Tutor] OverFlow Error
> Message-ID:
>        <CA+XJMJ5mVBWqVbTwhNwO4_5+XpdD_PnV2c66M1+vm6W+a7TySg at mail.gmail.com
> >
> Content-Type: text/plain; charset="iso-8859-1"
>
> How to correct this error?
>
> * OverflowError: Python int too large to convert to C long*
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: <
> http://mail.python.org/pipermail/tutor/attachments/20120121/f7b86624/attachment-0001.html
> >
>
> ------------------------------
>
> Message: 2
> Date: Sat, 21 Jan 2012 13:57:20 +0000
> From: Alan Gauld <alan.gauld at btinternet.com>
> To: tutor at python.org
> Subject: Re: [Tutor] OverFlow Error
> Message-ID: <jfeg80$dh5$1 at dough.gmane.org>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> On 21/01/12 13:10, Shreesh bhat wrote:
> > How to correct this error?
> >
> > * OverflowError: Python int too large to convert to C long*
>
>
> Could we have some context?
>
> What version of Python? What OS?
> What does your code look like?
> Can we see the full error trace please?
>
> Otherwise, based only on what you posted, the only advice
> I can give you is to use a smaller int!
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
> ------------------------------
>
> Message: 3
> Date: Sat, 21 Jan 2012 17:58:17 +0300
> From: George Nyoro <geonyoro at gmail.com>
> To: tutor at python.org
> Subject: Re: [Tutor] Tutor Digest, Vol 95, Issue 53
> Message-ID:
>        <CAM71YVE43XUXv5FmOvaXhL3Pv=-jvrvuOXEhU-fQky08oEHXCA at mail.gmail.com
> >
> Content-Type: text/plain; charset="iso-8859-1"
>
> Hey guys,
> I've been making an application and have made a delete method where the
> user can delete the instance of that application. e.g. if I have a table
> object, I need to be able to delete that instance from within the class and
> then it becomes accessible.
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: <
> http://mail.python.org/pipermail/tutor/attachments/20120121/d6796ae7/attachment-0001.html
> >
>
> ------------------------------
>
> Message: 4
> Date: Sun, 22 Jan 2012 02:07:45 +1100
> From: Steven D'Aprano <steve at pearwood.info>
> To: tutor at python.org
> Subject: Re: [Tutor] Tutor Digest, Vol 95, Issue 53
> Message-ID: <4F1AD4C1.3040406 at pearwood.info>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> George Nyoro wrote:
> > Hey guys,
> > I've been making an application and have made a delete method where the
> > user can delete the instance of that application. e.g. if I have a table
> > object, I need to be able to delete that instance from within the class
> and
> > then it becomes accessible.
>
> Did you want to ask a question, or are you just sharing?
>
>
> --
> Steven
>
>
>
> ------------------------------
>
> Message: 5
> Date: Sat, 21 Jan 2012 10:27:34 -0500
> From: Dave Angel <d at davea.name>
> To: George Nyoro <geonyoro at gmail.com>
> Cc: tutor at python.org
> Subject: Re: [Tutor] delete an object from method (was Tutor Digest)
> Message-ID: <4F1AD966.2070702 at davea.name>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> On 01/21/2012 09:58 AM, George Nyoro wrote:
> > Hey guys,
> > I've been making an application and have made a delete method where the
> > user can delete the instance of that application. e.g. if I have a table
> > object, I need to be able to delete that instance from within the class
> and
> > then it becomes accessible.
> >
>
> If you're going to misuse so many terms in one query, you'll need to
> supply some code, and tell us in what way it doesn't serve your needs.
>
> In the meantime,
>
> 1) Post a query by addressing it to "tutor at python.org," not by replying
> to  a digest message.  And if you must reply to a digest message, at
> least change the subject.  Thanks, though for deleting the digest content.
>
> 2) How do you expect to delete the instance of the application?  It's a
> funny term, but the only meaning I can come up with is you want to kill
> the application's process.
>
> 3) What's a table object?  If table is the name of your class, it really
> ought to be uppercase.
>
> 4) "from within the class" --  I'm guessing you mean from within a
> method of the class.
>
> 5) "then it becomes accessible" -- perhaps you mean inaccessible.
>
> 6) Please tell us the version of Python you're using and the operating
> system you're running on.
>
>
>
> --
>
> DaveA
>
>
>
> ------------------------------
>
> Message: 6
> Date: Sun, 22 Jan 2012 00:17:39 +0530
> From: Nikunj Badjatya <nikunjbadjatya at gmail.com>
> To: tutor <tutor at python.org>
> Subject: [Tutor] checking return status of 'ping' in windows
> Message-ID:
>        <CAOwQg9u6esoRAvUipX+ZshiFcbc_2gvQmYd8dZFcgQu6617NWA at mail.gmail.com
> >
> Content-Type: text/plain; charset="iso-8859-1"
>
> Hi All,
>
> I am using the following snippet to check the availability of an IP
> address. If that IP addr is found free than it can be used later on for
> further operations.
> Python ver 3.2
> Windows OS
>
> {{{
> pingret = subprocess.Popen('ping {0}'.format(IPaddr),
> shell=True,universal_newlines=True, \
>                    stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
> status = pingret.wait()
> if status == 0:
>    print("WARN  The IP given in the input is not free")
> .....
> .....
> }}}
>
> Normal ping operation on windows cmd prompt can give 3 outputs.
> 1) "destination host unreachable
> 2) "request timed out"
> 3) "Reply from 192.168.1.1: bytes=32 time=3ms TTL=64"
>
> Now,
> I was expecting the "status" in above snippet to hold '0' only in case of
> no. 3)
> But even when we have case 1), 'status' is holding '0'.
> i.e. The exit status of ping is 0, even when destination host is
> unreachable.!
>
> How do I make my snippet to work as desired. i.e even if destination host
> is unreachable, 'status' should hold '1'  and hold '0' only when it gets
> reply from that ip address.??
>
>
> Thanks,
>
> Nikunj
>
>
> --
> *7*Switch off as you go |*q*Recycle always | P Save Paper - Save Trees | Go
> Green
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: <
> http://mail.python.org/pipermail/tutor/attachments/20120122/0250ad3d/attachment-0001.html
> >
>
> ------------------------------
>
> Message: 7
> Date: Sat, 21 Jan 2012 23:53:42 +0100
> From: Hugo Arts <hugo.yoshi at gmail.com>
> To: Nikunj Badjatya <nikunjbadjatya at gmail.com>
> Cc: tutor <tutor at python.org>
> Subject: Re: [Tutor] checking return status of 'ping' in windows
> Message-ID:
>        <CAJmBOfni1jcSEwz65g76sXeuuM9oXepcZMsTXXrXECcoJdbkUQ at mail.gmail.com
> >
> Content-Type: text/plain; charset=UTF-8
>
> On Sat, Jan 21, 2012 at 7:47 PM, Nikunj Badjatya
> <nikunjbadjatya at gmail.com> wrote:
> > Hi All,
> >
> > I am using the following snippet to check the availability of an IP
> address.
> > If that IP addr is found free than it can be used later on for further
> > operations.
> > Python ver 3.2
> > Windows OS
> >
> > {{{
> > pingret = subprocess.Popen('ping {0}'.format(IPaddr),
> > shell=True,universal_newlines=True, \
> > ? ? ? ? ? ? ? ? ? ? stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
> > status = pingret.wait()
> > if status == 0:
> > ? ? print("WARN ?The IP given in the input is not free")
> > .....
> > .....
> > }}}
> >
> > Normal ping operation on windows cmd prompt can give 3 outputs.
> > 1) "destination host unreachable
> > 2) "request timed out"
> > 3) "Reply from 192.168.1.1: bytes=32 time=3ms TTL=64"
> >
> > Now,
> > I was expecting the "status" in above snippet to hold '0' only in case of
> > no. 3)
> > But even when we have case 1), 'status' is holding '0'.
> > i.e. The exit status of ping is 0, even when destination host is
> > unreachable.!
> >
>
> This appears to be windows specific. Linux ping will return an exit
> code of 1 if either zero responses are received or a packetcount and
> deadline are specified and not met. I'm not sure why it doesn't work
> that way on windows, but testing a bit for myself it seems to be the
> platform's fault and not python's, since calling EXIT 1 will correctly
> return a status code of 1.
>
> > How do I make my snippet to work as desired. i.e even if destination
> host is
> > unreachable, 'status' should hold '1' ?and hold '0' only when it gets
> reply
> > from that ip address.??
> >
>
> rather than using the wait() call, use Popen.communicate() which
> returns the output of the program, and check that directly for your
> three cases.
>
> HTH,
> Hugo
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 95, Issue 55
> *************************************
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120122/8e3ba4e9/attachment-0001.html>

From __peter__ at web.de  Sun Jan 22 09:25:13 2012
From: __peter__ at web.de (Peter Otten)
Date: Sun, 22 Jan 2012 09:25:13 +0100
Subject: [Tutor] OverflowError in lucky numbers script, was Re: Tutor Digest,
	Vol 95, Issue 55
References: <mailman.26988.1327186455.27777.tutor@python.org>
	<CA+XJMJ7__MSbr-669+D1meWacJdF+HJ8O0vpH7mHRgM+NQXC=g@mail.gmail.com>
Message-ID: <jfgh55$n8r$1@dough.gmane.org>

Shreesh bhat wrote:

> *Lucky Numbers*
> A number is called lucky if the sum of its digits, as well as the sum of
> the squares of its digits is a prime number. How many numbers between A
> and B are lucky?
> Input:
> The first line contains the number of test cases T. Each of the next T
> lines contains two integers, A and B.
> Output:
> Output T lines, one for each case containing the required answer for the
> corresponding case.
> 
> Constraints:
> 1 <= T <= 10000
> 1 <= A <= B <= 10^18
> Sample Input:
> 2
> 1 20
> 120 130
> Sample Output:
> 4
> 1
> Explanation:
> For the first case, the lucky numbers are 11, 12, 14, 16.
> For the second case, the only lucky number is 120.
> 
> 
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> My solution:
> 
> def isprime(n):
>   n=abs(int(n))
>   if n<2:
>     return False
>   if n==2:
>     return True
>   if not n & 1:
>     return False
>   for x in range(3,int(n**0.5)+1,2):
>     if n % x == 0:
>       return False
>   return True
> 
> def islucky(n):
>   sum1=0
>   sum2=0
>   while n!=0:
>     r=n%10
>     sum1+=r
>     sum2+=r*r
>     n=n/10

>   if isprime(sum1) & isprime(sum2):
>     return True
>   return False

Don't use '&' here, you're not bit-twiddling and the idiomatic code is

return isprime(sum1) and isprime(sum2)

which also has the advantage that it "short-ciruit"s, i. e. isprime(sum2) is 
only evaluated if isprime(sum1) is true.
 
> number=raw_input()
> 
> 
> for i in range(int(number)):
>     inp=raw_input()
>     a=inp.split()
>     startnum=int(a[0])
>     endnum=int(a[1])
>     li=map(islucky,xrange(startnum, endnum))
>     count=0
>     for j in li:
>         if j:
>             count+=1
>     print count
> 
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> 
> Traceback (most recent call last): File
> "/run-1327085301-1965755690/solution.py",
>  line 35, in li=map(islucky,xrange(startnum, endnum))
> OverflowError: Python int too large to convert to C long
> 
> 
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> It shows this error for very large numbers or slows down with large
> numbers. I m using Ubuntu 32-bit.

The arguments of xrange() are limited to C integers, they cannot be larger 
than sys.maxint (2**31-1 on a 32-bit system or 2**63-1 on a 64-bit system). 
range() can handle larger numbers, but you'll always see a slowdown -- 
larger numbers have more digits and (on average) larger sums, and thus take 
longer to test.



From bugcy013 at gmail.com  Sun Jan 22 10:23:00 2012
From: bugcy013 at gmail.com (Ganesh Kumar)
Date: Sun, 22 Jan 2012 14:53:00 +0530
Subject: [Tutor] Setting Network settings from Python/Djang
Message-ID: <CAJzooYegzGwc1B9eOv+ZPNvUTcBcTGJDtBjrEuGdsDyRaoHVSg@mail.gmail.com>

I'm working on a simple web interface for an embedded computer. The
computer will ship with a static default ip that will then need to be
updated by the install tech who may not be tech/linux savvy.

Basicly I need to change the following system settings from a Django app.

   1. IP Addres
   2. Subnet
   3. Default Gateway
   4. DNS Servers 1&2

I realize that I can could just overwrite the config files in linux but I
was wondering if there is a more "Python" way of doing it.

I want any ready to use module is there, please guide me.


-Ganesh.

Did I learn something today? If not, I wasted it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120122/20da0417/attachment.html>

From alan.gauld at btinternet.com  Sun Jan 22 11:05:01 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 22 Jan 2012 10:05:01 +0000
Subject: [Tutor] Tutor Digest, Vol 95, Issue 55
In-Reply-To: <CA+XJMJ7__MSbr-669+D1meWacJdF+HJ8O0vpH7mHRgM+NQXC=g@mail.gmail.com>
References: <mailman.26988.1327186455.27777.tutor@python.org>
	<CA+XJMJ7__MSbr-669+D1meWacJdF+HJ8O0vpH7mHRgM+NQXC=g@mail.gmail.com>
Message-ID: <jfgn0e$mdv$1@dough.gmane.org>

On 22/01/12 06:11, Shreesh bhat wrote:

Here goes some general comments that will make it esier to understand 
your code and therefore, hopefully, the problem.

> def isprime(n):
>      ....

> def islucky(n):
        .....

There are more efficient ways of doing both tests
but I'll igniore that for now.

> number=raw_input()

It helps to include a prompt in raw_input.
Not only does it help the user know what to type but it can help the 
reader understand what the value represents. This is apparently
a number but what the number is for I have no idea. Which leads to the 
next comment, that variable names should reflect the pourpose of the 
variable not its type.

> for i in range(int(number)):
>      inp=raw_input()

As above, I have no idea what inp represents so I can
only guess at its content

>      a=inp.split()
>      startnum=int(a[0])
>      endnum=int(a[1])

This might be a good place to insert a print statement
showing the values...

>      li=map(islucky,xrange(startnum, endnum))

And here is where you get the error, so presumably you have used 
integers which are too big for xrange?

>      count=0
>      for j in li:
>          if j:
>              count+=1
 >      print count

You could just use the count method of the list:

  print li.count(True)


> It shows this error for very large numbers

Yes thats what it says, the numbers are too big for xrange
to process. You need to find another way to do it, or
build your own pure python equivalent of xrange() - but
that will be even slower!.

> or slows down with large numbers.

large numbers mean lots of iterations. They also mean that Python is 
having to work harder because it's not using the underlying C integers.
Thats the price you pay for processing big numbers. But think on the 
bright side: its still faster than you could do it using pencil and 
paper! :-)

But you can speed it up a bit by making your tests more efficient...

> On Sun, Jan 22, 2012 at 4:24 AM, <tutor-request at python.org
> <mailto:tutor-request at python.org>> wrote:
>    ....
>
>     When replying, please edit your Subject line so it is more specific
>     than "Re: Contents of Tutor digest..."


Please follow this instruction...
And also, while you are at it trim all the content thats not relevant.
Some people pay for their internet access by the byte...

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


From steve at pearwood.info  Sun Jan 22 11:52:02 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 22 Jan 2012 21:52:02 +1100
Subject: [Tutor] Tutor Digest, Vol 95, Issue 55
In-Reply-To: <CA+XJMJ7__MSbr-669+D1meWacJdF+HJ8O0vpH7mHRgM+NQXC=g@mail.gmail.com>
References: <mailman.26988.1327186455.27777.tutor@python.org>
	<CA+XJMJ7__MSbr-669+D1meWacJdF+HJ8O0vpH7mHRgM+NQXC=g@mail.gmail.com>
Message-ID: <4F1BEA52.60901@pearwood.info>

Shreesh bhat wrote:
> *Lucky Numbers*
> A number is called lucky if the sum of its digits, as well as the sum of
> the squares of its digits is a prime number. How many numbers between A and
> B are lucky?

Very little of this is relevant to your problem. In the future, please provide 
a short, self-contained, correct example that demonstrates the problem.

http://sscce.org/

Here is the shortest example I can see, a single line of code:

xrange(2**31-1, 2**31)

which gives the same error:

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
OverflowError: long int too large to convert to int

(The error message itself can vary from version to version.)

Possible solutions:

* Don't use xrange, write your own generator which will do the job.

def my_xrange(start, stop):
     i = start
     while i < stop:
         yield i
         i += 1


This will work, but will be much slower.


* Scale your numbers from time to time, to avoid them getting too big.
* Can you rethink your algorithm and avoid needing such huge numbers?
* Just accept that your function can't handle such huge numbers.



> Traceback (most recent call last): File
> "/run-1327085301-1965755690/solution.py",
>  line 35, in li=map(islucky,xrange(startnum, endnum))
> OverflowError: Python int too large to convert to C long
> 
> -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> It shows this error for very large numbers or slows down with large numbers.


It slows down for large numbers because you have written a very inefficient 
isprime() function.



> I m using Ubuntu 32-bit.


What is more important than the version of your operating system is the 
version of Python.


> On Sun, Jan 22, 2012 at 4:24 AM, <tutor-request at python.org> wrote:
[snip hundreds of irrelevant lines]

Please do not reply to digest posts without deleting the unnecessary quoting, 
and setting the subject line appropriately.

You may find it useful to read this:

http://catb.org/esr/faqs/smart-questions.html



-- 
Steven

From shreeshbhat90 at gmail.com  Sun Jan 22 12:37:21 2012
From: shreeshbhat90 at gmail.com (Shreesh bhat)
Date: Sun, 22 Jan 2012 17:07:21 +0530
Subject: [Tutor] OverflowError in lucky numbers script
Message-ID: <CA+XJMJ7H3rd2P3H3vSNLu+U-Z6FLdR9y0ui0B40+gz_Kb7FZJQ@mail.gmail.com>

I m using Python 2.7
Steven wrote:
" Scale your numbers from time to time, to avoid them getting too big "
What does this mean?

inp refers to the sample input test case I have given at first.Its a string
containing two numbers,
The program has to handle large numbers till 10**18 and also has to execute
considerably fast (within 16 CPU time).

Using xrange() causes the OveflowError,Whereas using range() causes too
many items
Is writing my own generator only solution? Or is there another way in which
i can generate big numbers and in considerably fast manner?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120122/0ca86284/attachment.html>

From ian.douglas at iandouglas.com  Sun Jan 22 13:30:41 2012
From: ian.douglas at iandouglas.com (ian douglas)
Date: Sun, 22 Jan 2012 04:30:41 -0800
Subject: [Tutor] Setting Network settings from Python/Djang
In-Reply-To: <CAJzooYegzGwc1B9eOv+ZPNvUTcBcTGJDtBjrEuGdsDyRaoHVSg@mail.gmail.com>
References: <CAJzooYegzGwc1B9eOv+ZPNvUTcBcTGJDtBjrEuGdsDyRaoHVSg@mail.gmail.com>
Message-ID: <CAFNSOgXm+bgEXssXzp=GyYmCVfR4soP6dK=wcEeWW=e0wbGw0A@mail.gmail.com>

Well DNS would be easy, just modify /etc/resolve.conf ... the other files
you need to modify would depend on your distro because they all do
something slightly different it seems.
On Jan 22, 2012 3:25 AM, "Ganesh Kumar" <bugcy013 at gmail.com> wrote:

> I'm working on a simple web interface for an embedded computer. The
> computer will ship with a static default ip that will then need to be
> updated by the install tech who may not be tech/linux savvy.
>
> Basicly I need to change the following system settings from a Django app.
>
>    1. IP Addres
>    2. Subnet
>    3. Default Gateway
>    4. DNS Servers 1&2
>
> I realize that I can could just overwrite the config files in linux but I
> was wondering if there is a more "Python" way of doing it.
>
> I want any ready to use module is there, please guide me.
>
>
> -Ganesh.
>
> Did I learn something today? If not, I wasted it.
>
> _______________________________________________
> 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/20120122/d9571504/attachment.html>

From __peter__ at web.de  Sun Jan 22 13:39:47 2012
From: __peter__ at web.de (Peter Otten)
Date: Sun, 22 Jan 2012 13:39:47 +0100
Subject: [Tutor] OverflowError in lucky numbers script
References: <CA+XJMJ7H3rd2P3H3vSNLu+U-Z6FLdR9y0ui0B40+gz_Kb7FZJQ@mail.gmail.com>
Message-ID: <jfh02e$cpn$1@dough.gmane.org>

Shreesh bhat wrote:

> I m using Python 2.7
> Steven wrote:
> " Scale your numbers from time to time, to avoid them getting too big "
> What does this mean?
> 
> inp refers to the sample input test case I have given at first.Its a
> string containing two numbers,
> The program has to handle large numbers till 10**18 and also has to
> execute considerably fast (within 16 CPU time).
> 
> Using xrange() causes the OveflowError,Whereas using range() causes too
> many items
> Is writing my own generator only solution? Or is there another way in
> which i can generate big numbers and in considerably fast manner?

If you look at the numbers

$ python -m timeit -s'from lucky_number import islucky; start=10**10; 
stop=10**10+1000' 'i = start' 'while i < stop:' ' islucky(i); i += 1'
100 loops, best of 3: 10.8 msec per loop

$ python -m timeit -s'from lucky_number import islucky; start=10**10; 
stop=10**10+1000' 'i = start' 'while i < stop:' ' i += 1'
10000 loops, best of 3: 145 usec per loop

you'll see that counting even with a primitive while loop takes less than 
two percent of the total time spent. This means you don't have to worry 
about that part of your script until you have come up with a luckiness test 
that is much faster than your current one.


From d at davea.name  Sun Jan 22 13:54:59 2012
From: d at davea.name (Dave Angel)
Date: Sun, 22 Jan 2012 07:54:59 -0500
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <CA+XJMJ7H3rd2P3H3vSNLu+U-Z6FLdR9y0ui0B40+gz_Kb7FZJQ@mail.gmail.com>
References: <CA+XJMJ7H3rd2P3H3vSNLu+U-Z6FLdR9y0ui0B40+gz_Kb7FZJQ@mail.gmail.com>
Message-ID: <4F1C0723.7080809@davea.name>

On 01/22/2012 06:37 AM, Shreesh bhat wrote:
> I m using Python 2.7
> Steven wrote:
> " Scale your numbers from time to time, to avoid them getting too big"
> What does this mean?
>
> inp refers to the sample input test case I have given at first.Its a string
> containing two numbers,
> The program has to handle large numbers till 10**18 and also has to execute
> considerably fast (within 16 CPU time).
>
> Using xrange() causes the OveflowError,Whereas using range() causes too
> many items
> Is writing my own generator only solution? Or is there another way in which
> i can generate big numbers and in considerably fast manner?
Without knowing any constraints on the range (other than the limits are 
each less than 10**18), you either have to write your own generator or 
do a while loop.   That's not your problem.  Write one of them, and make 
sure your program now gets correct answers.

Now you're apparently adding a new constraint "execute considerably fast 
(within 16 CPU time)".  No idea what that means, but perhaps you left 
out the unit.  Do you mean 16 minutes?

When a program is correct, but too slow, you may need faster functions 
(like xrange is usually faster than range, and both are faster than one 
your wrote by hand).  Or you may need a better algorithm.

For each individual number, I think you would find that the bulk of the 
time is spent checking isprime().  There are functions that are much 
faster than the way you're doing, but I expect the time problem doesn't 
occur till you're checking lots of such numbers.

When you have slow functions called lots of times, you can either speed 
up the function, or reduce the number of times its called.

What I would do is figure out what the largest sum might be (9 * 19, 
more or less).  Calculate the isprime(n) and isprime(n*n) for each of 
those, and save them in a table.  Now your main loop can just sum the 
digits and consult the table.  If that's not fast enough, optimize the 
way you sum the digits.


-- 

DaveA


From alan.gauld at btinternet.com  Sun Jan 22 19:24:16 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 22 Jan 2012 18:24:16 +0000
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <CA+XJMJ7H3rd2P3H3vSNLu+U-Z6FLdR9y0ui0B40+gz_Kb7FZJQ@mail.gmail.com>
References: <CA+XJMJ7H3rd2P3H3vSNLu+U-Z6FLdR9y0ui0B40+gz_Kb7FZJQ@mail.gmail.com>
Message-ID: <jfhk8h$e10$1@dough.gmane.org>

On 22/01/12 11:37, Shreesh bhat wrote:

> Steven wrote:
> " Scale your numbers from time to time, to avoid them getting too big "
> What does this mean?

It could be done in various ways but one simple example is,

low = 10000000000
hi =  10000000010

for n in range(low,hi):
     ... code uses n ...

could also be written

span = hi-low
for n in range(span)  # ie. range(10)
     val = low + n
     .... code uses val ...

Now the value given to range is a very small number...
Of course if low is zero and hi is large you need to think
again, so maybe you can break the range into chunks (eg. what
about using the square root?)? And process each chunk as above?

As I say there are lots of ways to do it, you need to think of one that 
works for your data.

> inp refers to the sample input test case I have given at first.Its a
> string containing two numbers,

ok, so it contains the lo-hi pair?
Why not call it lo_hi

lo_hi = raw_input('Enter the low and high numbers')

Can you see how the combination of variable name and prompt string tells 
the reader what is going on?


> The program has to handle large numbers till 10**18 and also has to
> execute considerably fast (within 16 CPU time).

I can promise you it will never run in 16 clock cycles...

> Is writing my own generator only solution? Or is there another way in
> which i can generate big numbers and in considerably fast manner?

Your problem is to avoid generating very big numbers wherever possible.
Construct them for output as needed but do the processing using smaller 
ones. Just because Python supports arbitrarily large integers does not 
mean you should use them in every case...

HTH,

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


From deshpande.jaidev at gmail.com  Sun Jan 22 23:10:26 2012
From: deshpande.jaidev at gmail.com (Jaidev Deshpande)
Date: Mon, 23 Jan 2012 03:40:26 +0530
Subject: [Tutor] Importing functions in IPython
Message-ID: <CAB=suE=UkwhKRJn-BnO3OKnih8WG5uGuHu9TVf+XQXfKcB+C=g@mail.gmail.com>

Dear List,

Suppose I have a function myfunc() in a module called mymodule.py

As usual, I import this function in IPython with

In[1]: from mymodule import myfunc

Now if I find that there is something wrong with myfunc, I can open
mymodule.py with a suitable editor and make the required changes.

Now when I delete the original function and import the changed one,

In[2]: del myfunc

In[3]: from mymodule import myfunc

it doesn't work as per the new changes. I have to close IPython and
start all over again.

Is there a less cumbersome way to do this, preferably without closing IPython?

Thanks

From steve at pearwood.info  Sun Jan 22 23:39:57 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 23 Jan 2012 09:39:57 +1100
Subject: [Tutor] Importing functions in IPython
In-Reply-To: <CAB=suE=UkwhKRJn-BnO3OKnih8WG5uGuHu9TVf+XQXfKcB+C=g@mail.gmail.com>
References: <CAB=suE=UkwhKRJn-BnO3OKnih8WG5uGuHu9TVf+XQXfKcB+C=g@mail.gmail.com>
Message-ID: <20120122223957.GB4148@ando>

On Mon, Jan 23, 2012 at 03:40:26AM +0530, Jaidev Deshpande wrote:
> Dear List,
> 
> Suppose I have a function myfunc() in a module called mymodule.py
[...]
> Now when I delete the original function and import the changed one,
> 
> In[2]: del myfunc
> In[3]: from mymodule import myfunc
> 
> it doesn't work as per the new changes. I have to close IPython and
> start all over again.

As far as I know, this is not an IPython specific problem, but is due to 
the way Python imports modules.

Here are two alternatives:

1) Instead of "from mymodule import myfunc", instead use 

import mymodule
result = mymodule.myfunc()  # not myfunc() on its own

After changing the source file, do "reload(mymodule)" and Python will 
pick up the changes.

2) You can manually force a reload:

import sys
del sys.modules['mymodule']
from mymodule import myfunc

But two warnings:

* reload() is very simple-minded. It is not guaranteed to change the 
behaviour of existing objects just because the module is reloaded. The 
most common example of this is if you use classes: reloading the module 
after modifying the class will NOT change the behaviour of any existing 
instances. E.g.:

import mymodule
instance = mymodule.MyClass()
# now edit MyClass in mymodule and change the method behaviour
reload(mymodule)
instance.method()  # instance will keep the OLD behaviour, not the new

* Because reload() so often doesn't work as expected, in Python 3, it 
has been removed from the built-ins and is now found in the imp module.


-- 
Steven

From alan.gauld at btinternet.com  Sun Jan 22 23:43:29 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 22 Jan 2012 22:43:29 +0000
Subject: [Tutor] Importing functions in IPython
In-Reply-To: <CAB=suE=UkwhKRJn-BnO3OKnih8WG5uGuHu9TVf+XQXfKcB+C=g@mail.gmail.com>
References: <CAB=suE=UkwhKRJn-BnO3OKnih8WG5uGuHu9TVf+XQXfKcB+C=g@mail.gmail.com>
Message-ID: <jfi3ei$e95$1@dough.gmane.org>

On 22/01/12 22:10, Jaidev Deshpande wrote:

> In[1]: from mymodule import myfunc
>
> In[3]: from mymodule import myfunc
>
> it doesn't work as per the new changes. I have to close IPython and
> start all over again.

You can use reload() to reload the entire module, but I confess I don't 
know how to reload a function using import like that... reload doesn't 
seem to have any option for that

I'll watch this space to see if anyone else knows how.
Meantime you can try just using

import mymodule
mymodule.myfunc()

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


From bgailer at gmail.com  Sun Jan 22 23:51:52 2012
From: bgailer at gmail.com (bob gailer)
Date: Sun, 22 Jan 2012 17:51:52 -0500
Subject: [Tutor] Importing functions in IPython
In-Reply-To: <CAB=suE=UkwhKRJn-BnO3OKnih8WG5uGuHu9TVf+XQXfKcB+C=g@mail.gmail.com>
References: <CAB=suE=UkwhKRJn-BnO3OKnih8WG5uGuHu9TVf+XQXfKcB+C=g@mail.gmail.com>
Message-ID: <4F1C9308.2020606@gmail.com>

On 1/22/2012 5:10 PM, Jaidev Deshpande wrote:
> Dear List,
>
> Suppose I have a function myfunc() in a module called mymodule.py
>
> As usual, I import this function in IPython with
>
> In[1]: from mymodule import myfunc
>
> Now if I find that there is something wrong with myfunc, I can open
> mymodule.py with a suitable editor and make the required changes.
>
> Now when I delete the original function and import the changed one,
>
> In[2]: del myfunc
>
> In[3]: from mymodule import myfunc
>
> it doesn't work as per the new changes. I have to close IPython and
> start all over again.
>
> Is there a less cumbersome way to do this, preferably without closing IPython?
in "normal" python:

import sys
reload(sys.modules['mymodule '])
from mymodule import myfunc

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


From bgailer at gmail.com  Sun Jan 22 23:53:19 2012
From: bgailer at gmail.com (bob gailer)
Date: Sun, 22 Jan 2012 17:53:19 -0500
Subject: [Tutor] Importing functions in IPython
In-Reply-To: <jfi3ei$e95$1@dough.gmane.org>
References: <CAB=suE=UkwhKRJn-BnO3OKnih8WG5uGuHu9TVf+XQXfKcB+C=g@mail.gmail.com>
	<jfi3ei$e95$1@dough.gmane.org>
Message-ID: <4F1C935F.2060601@gmail.com>

On 1/22/2012 5:43 PM, Alan Gauld wrote:
> On 22/01/12 22:10, Jaidev Deshpande wrote:
>
>> In[1]: from mymodule import myfunc
>>
>> In[3]: from mymodule import myfunc
>>
>> it doesn't work as per the new changes. I have to close IPython and
>> start all over again.
>
> You can use reload() to reload the entire module, but I confess I 
> don't know how to reload a function using import like that... reload 
> doesn't seem to have any option for that
>
> I'll watch this space to see if anyone else knows how.

Good idea. And now you know.


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


From d at davea.name  Mon Jan 23 01:14:30 2012
From: d at davea.name (Dave Angel)
Date: Sun, 22 Jan 2012 19:14:30 -0500
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <CA+XJMJ6H0sMWib-ZbENFfQYrHWy=vFnW+RV3ta7UmiuZX72y1Q@mail.gmail.com>
References: <CA+XJMJ6H0sMWib-ZbENFfQYrHWy=vFnW+RV3ta7UmiuZX72y1Q@mail.gmail.com>
Message-ID: <4F1CA666.8080203@davea.name>

You sent me this message privately, instead of on the list (use 
Reply-All in most mail programs).  Two problems with that:   1) nobody 
else gets to help  2) I don't give private help, except as a contractor.

On 01/22/2012 12:44 PM, Shreesh bhat wrote:
> *Lucky numbers:*
> def sieve(maxi):
>    primes = range(2,maxi+1)
>    for i in primes:
>      j = 2
>      while i * j<= primes[-1]:
>        if i * j in primes:
>          primes.remove(i*j)
>        j += 1
>    return primes
>
> maxi=(9**2)*19
> tab=sieve(maxi)
> table={}
> for i in tab:
>      table[i]=0
>
> def isprime(n):
>      return table.has_key(n)
>
> count=0
>
> def islucky(n):
>    global count
>    sum1=0
>    sum2=0
>    for letter in str(n):
>      tmp=ord(letter)-48
>      sum1+=tmp
>      sum2+=tmp**2
>    if isprime(sum1):
>      if isprime(sum2):
>        count+=1
>
> number=raw_input()
> def execute():
>    global count
>    for i in range(int(number)):
>        inp=raw_input()
>        a=inp.split()
>        startnum=int(a[0])
>        endnum=int(a[1])
>        count=0
>        while startnum != endnum:
>            islucky(startnum)
>            startnum+=1
>        print count
>
> execute()
>
> Hi Sir,
> The program still doesn't work with "consult-table" approach.

Define "doesn't work".  If you give a specific trace-back message, 
somebody is bound to recognize the problem.  Or if it doesn't give an 
exception, describe in what way the answer is wrong.  Or if it's 
completely correct, but simply too slow, then say so.

> I have also optimised digit's sum method.
> Can you please tell me another method to work around it to get more
> execution speed?
>

What part is slow?  Calculating the table, or looping through your while 
loop?


-- 

DaveA

From suryak at live.com  Mon Jan 23 03:08:52 2012
From: suryak at live.com (Surya K)
Date: Mon, 23 Jan 2012 07:38:52 +0530
Subject: [Tutor] how to handle very large numbers
Message-ID: <SNT130-W55154B68C30987D8E151CEA48A0@phx.gbl>


Well, 
I have been doing a puzzle where I have to deal with number 10^18. A variable can store that value but can't do operations.Ex: If I use range() on it, it shows overflow error.
So, How do I handle this. I have to use range() for that number.. in this instance.
Also mention how to handle in other cases too (A small tutorial/ book would be appreciated )

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

From d at davea.name  Mon Jan 23 03:28:14 2012
From: d at davea.name (Dave Angel)
Date: Sun, 22 Jan 2012 21:28:14 -0500
Subject: [Tutor] how to handle very large numbers
In-Reply-To: <SNT130-W55154B68C30987D8E151CEA48A0@phx.gbl>
References: <SNT130-W55154B68C30987D8E151CEA48A0@phx.gbl>
Message-ID: <4F1CC5BE.8020501@davea.name>

On 01/22/2012 09:08 PM, Surya K wrote:
> Well,
> I have been doing a puzzle where I have to deal with number 10^18. A variable can store that value but can't do operations.Ex: If I use range() on it, it shows overflow error.
> So, How do I handle this. I have to use range() for that number.. in this instance.
> Also mention how to handle in other cases too (A small tutorial/ book would be appreciated )
>
> Thanks 		 	   		
>
Check out the ongoing thread of someone who's probably doing the same 
assignment.  Subject is "OverflowError in lucky numbers script"

Short answers for range():  You need to specify your Python version.

In Python 2.7, range() has no problem handling longs as its arguments.  
It does have a problem when the number of items gets too large for 
memory.  You could avoid the memory problem by using xrange(), which is 
restricted to ints.  You can, however, write a generator to operate over 
a series of such longs.

I don't believe Python 3.x range has any constraints, and it's already a 
generator, so you'll have to be more specific about what your 
environment is.


-- 

DaveA


From shreeshbhat90 at gmail.com  Mon Jan 23 07:15:58 2012
From: shreeshbhat90 at gmail.com (Shreesh bhat)
Date: Mon, 23 Jan 2012 11:45:58 +0530
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <CA+XJMJ7F0P-wyBjyV17KMqO8EPKY5FdUqCKkr=TuBrMN1tO39w@mail.gmail.com>
References: <CA+XJMJ7F0P-wyBjyV17KMqO8EPKY5FdUqCKkr=TuBrMN1tO39w@mail.gmail.com>
Message-ID: <CA+XJMJ4Dz9tJXWU=wGGp6Z2_aVDth3aXgjWUV-7FXETc1sU0vw@mail.gmail.com>

Calculating the table is fast.
I think either my luckiness test (where i find the sum of all digits and
sum of squares of all digits of a large number)
or generating numbers is slow.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120123/ea5f8389/attachment.html>

From shreeshbhat90 at gmail.com  Mon Jan 23 07:10:53 2012
From: shreeshbhat90 at gmail.com (Shreesh bhat)
Date: Mon, 23 Jan 2012 11:40:53 +0530
Subject: [Tutor] OverflowError in lucky numbers script
Message-ID: <CA+XJMJ7F0P-wyBjyV17KMqO8EPKY5FdUqCKkr=TuBrMN1tO39w@mail.gmail.com>

Thank you all for helping me understand the overflow error.
I m a newbie on mailing lists.I apologize for my errors.
Program:

def sieve(maxi):
  primes = range(2,maxi+1)
  for i in primes:
    j = 2
    while i * j <= primes[-1]:
      if i * j in primes:
        primes.remove(i*j)
      j += 1
  return primes

maxi=(10**2)*18   #Generating the table till the largest possible prime
tab=sieve(maxi)
table={}
for i in tab:
    table[i]=0

def isprime(n):
    return table.has_key(n)

count=0

def islucky(n):   # modified islucky function
  global count
  sum1=0
  sum2=0
  for letter in str(n):
    tmp=ord(letter)-48
    sum1+=tmp
    sum2+=tmp**2
  if isprime(sum1):
    if isprime(sum2):
      count+=1

number=raw_input()  # Number of test cases.Its constraint (1,10000)
def execute():
  global count
  for i in range(int(number)):
      inp=raw_input()    # startnumber and endnumber pair. Its constraint
(1,10**18)
      a=inp.split()
      startnum=int(a[0])
      endnum=int(a[1])
      count=0
      while startnum != endnum:
          islucky(startnum)
          startnum+=1
      print count

execute()

The program is executing correctly but it has to execute 16 seconds for the
constraints.
I have optimized the way i sum up digits and used "consult-table" approach.
Still the program doesn't reach the 16 seconds target.
How to achieve this target?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120123/d97dbbc0/attachment-0001.html>

From breamoreboy at yahoo.co.uk  Mon Jan 23 08:02:13 2012
From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi)
Date: Mon, 23 Jan 2012 07:02:13 +0000
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <CA+XJMJ4Dz9tJXWU=wGGp6Z2_aVDth3aXgjWUV-7FXETc1sU0vw@mail.gmail.com>
References: <CA+XJMJ7F0P-wyBjyV17KMqO8EPKY5FdUqCKkr=TuBrMN1tO39w@mail.gmail.com>
	<CA+XJMJ4Dz9tJXWU=wGGp6Z2_aVDth3aXgjWUV-7FXETc1sU0vw@mail.gmail.com>
Message-ID: <jfj0lo$96g$1@dough.gmane.org>

On 23/01/2012 06:15, Shreesh bhat wrote:
> Calculating the table is fast.
> I think either my luckiness test (where i find the sum of all digits and
> sum of squares of all digits of a large number)
> or generating numbers is slow.
>

Don't think, know :) Tools like the profile or timeit modules are there 
for a purpose so use them.

Cheers.

Mark Lawrence.



From __peter__ at web.de  Mon Jan 23 09:13:13 2012
From: __peter__ at web.de (Peter Otten)
Date: Mon, 23 Jan 2012 09:13:13 +0100
Subject: [Tutor] OverflowError in lucky numbers script
References: <CA+XJMJ7F0P-wyBjyV17KMqO8EPKY5FdUqCKkr=TuBrMN1tO39w@mail.gmail.com>
Message-ID: <jfj4qh$1h9$1@dough.gmane.org>

Shreesh bhat wrote:

> Thank you all for helping me understand the overflow error.
> I m a newbie on mailing lists.I apologize for my errors.
> Program:

[snip code]

> The program is executing correctly but it has to execute 16 seconds for
> the constraints.
> I have optimized the way i sum up digits and used "consult-table"
> approach. Still the program doesn't reach the 16 seconds target.
> How to achieve this target?

What is the exact dataset for which you are trying to reach that execution 
time limit? Please give the values for start and end numbers.

How far off is your current solution, i. e. how many seconds does it need to 
finish?

I am asking because if you are almost there it makes sense to try and 
optimise your current script a little more, but if you are orders of 
magnitude away from your goal you may need a completely different approach.


From alan.gauld at btinternet.com  Mon Jan 23 11:08:50 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 23 Jan 2012 10:08:50 +0000
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <CA+XJMJ7F0P-wyBjyV17KMqO8EPKY5FdUqCKkr=TuBrMN1tO39w@mail.gmail.com>
References: <CA+XJMJ7F0P-wyBjyV17KMqO8EPKY5FdUqCKkr=TuBrMN1tO39w@mail.gmail.com>
Message-ID: <jfjbji$g5r$1@dough.gmane.org>

On 23/01/12 06:10, Shreesh bhat wrote:
>
> def sieve(maxi):
>    primes = range(2,maxi+1)

You can reduce the size of primes by only storing the odd numbers.
range takes a third parameter that sets the stepsize, you cxan
use that to skip evens...

>    for i in primes:
>      j = 2

you can then start here with j=3...

>      while i * j <= primes[-1]:
>        if i * j in primes:
>          primes.remove(i*j)

I'm not sure which is faster but I suspect list comprehensions
could be used here too at the expense of consuming more memory.

primes = [num for num in primes if i*j in primes]

but the while loop stops earlier so it's hard to be sure which
is more efficient unless you try it.

>        j += 1
>    return primes
>
> maxi=(10**2)*18   #Generating the table till the largest possible prime
> tab=sieve(maxi)
> table={}
> for i in tab:
>      table[i]=0
>
> def isprime(n):
>      return table.has_key(n)
>
> count=0
>
> def islucky(n):   # modified islucky function
>    global count
>    sum1=0
>    sum2=0
>    for letter in str(n):
>      tmp=ord(letter)-48
>      sum1+=tmp
>      sum2+=tmp**2

>    if isprime(sum1):
>      if isprime(sum2):
>        count+=1

This last should be marginally faster if you use an and test:

     if isprime(sum1) and isprime(sum2):
         count+=1

> number=raw_input()  # Number of test cases.Its constraint (1,10000)

Put the description as the prompt - make life easier for your user, even 
if it is only you! Learn good habits early.

number=raw_input("Number of test cases(1-10000).")


> def execute():
>    global count
>    for i in range(int(number)):
>        inp=raw_input()    # startnumber and endnumber pair. Its
> constraint (1,10**18)

Same here:

inp=raw_input("startnumber and endnumber pair(1-10**18)")

>        a=inp.split()
>        startnum=int(a[0])
>        endnum=int(a[1])
>        count=0
>        while startnum != endnum:

!= is a risky strategy, it can lead to accidental infinite loops. Better 
to use

while startnum < endnum:

and while we are at it, do you really mean not to test endnum?

>            islucky(startnum)
>            startnum+=1
>        print count
>
> execute()
>
> The program is executing correctly but it has to execute 16 seconds for
> the constraints.

So how close are you? That gives us a clue on how much farther we need 
to optimise...

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


From suryak at live.com  Mon Jan 23 13:32:50 2012
From: suryak at live.com (Surya K)
Date: Mon, 23 Jan 2012 18:02:50 +0530
Subject: [Tutor] how to handle very large numbers
In-Reply-To: <4F1CC5BE.8020501@davea.name>
References: <SNT130-W55154B68C30987D8E151CEA48A0@phx.gbl>,
	<4F1CC5BE.8020501@davea.name>
Message-ID: <SNT130-W436449F87B13C31E1EB3C8A48A0@phx.gbl>




> Date: Sun, 22 Jan 2012 21:28:14 -0500
> From: d at davea.name
> To: suryak at live.com
> CC: tutor at python.org
> Subject: Re: [Tutor] how to handle very large numbers
> 
> On 01/22/2012 09:08 PM, Surya K wrote:
> > Well,
> > I have been doing a puzzle where I have to deal with number 10^18. A variable can store that value but can't do operations.Ex: If I use range() on it, it shows overflow error.
> > So, How do I handle this. I have to use range() for that number.. in this instance.
> > Also mention how to handle in other cases too (A small tutorial/ book would be appreciated )
> >
> > Thanks 		 	   		
> >
> Check out the ongoing thread of someone who's probably doing the same 
> assignment.  Subject is "OverflowError in lucky numbers script"
> 
> Short answers for range():  You need to specify your Python version.
> 
> In Python 2.7, range() has no problem handling longs as its arguments.  
> It does have a problem when the number of items gets too large for 
> memory.  You could avoid the memory problem by using xrange(), which is 
> restricted to ints.  You can, however, write a generator to operate over 
> a series of such longs.
> 
> I don't believe Python 3.x range has any constraints, and it's already a 
> generator, so you'll have to be more specific about what your 
> environment is.
> 
> 
> -- 
> 
> DaveA
> 

I am using Python 2.7. I don't think range() can take large values.
example: 
I took a = 1000000000000000000 (10^18); This is the max limit in a puzzle.
python showed the following error :OverflowError: range() has too many items.
I even tried using xrange(), I didn't solve the issue..
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120123/ab713555/attachment.html>

From d at davea.name  Mon Jan 23 14:00:35 2012
From: d at davea.name (Dave Angel)
Date: Mon, 23 Jan 2012 08:00:35 -0500
Subject: [Tutor] how to handle very large numbers
In-Reply-To: <SNT130-W436449F87B13C31E1EB3C8A48A0@phx.gbl>
References: <SNT130-W55154B68C30987D8E151CEA48A0@phx.gbl>,
	<4F1CC5BE.8020501@davea.name>
	<SNT130-W436449F87B13C31E1EB3C8A48A0@phx.gbl>
Message-ID: <4F1D59F3.5090408@davea.name>

On 01/23/2012 07:32 AM, Surya K wrote:
>
>
>
>> Date: Sun, 22 Jan 2012 21:28:14 -0500
>> From: d at davea.name
>> To: suryak at live.com
>> CC: tutor at python.org
>> Subject: Re: [Tutor] how to handle very large numbers
>>
>> On 01/22/2012 09:08 PM, Surya K wrote:
>>> Well,
>>> I have been doing a puzzle where I have to deal with number 10^18. A variable can store that value but can't do operations.Ex: If I use range() on it, it shows overflow error.
>>> So, How do I handle this. I have to use range() for that number.. in this instance.
>>> Also mention how to handle in other cases too (A small tutorial/ book would be appreciated )
>>>
>>> Thanks 		 	   		
>>>
>> Check out the ongoing thread of someone who's probably doing the same
>> assignment.  Subject is "OverflowError in lucky numbers script"
>>
>> Short answers for range():  You need to specify your Python version.
>>
>> In Python 2.7, range() has no problem handling longs as its arguments.
>> It does have a problem when the number of items gets too large for
>> memory.  You could avoid the memory problem by using xrange(), which is
>> restricted to ints.  You can, however, write a generator to operate over
>> a series of such longs.
>>
>> I don't believe Python 3.x range has any constraints, and it's already a
>> generator, so you'll have to be more specific about what your
>> environment is.
>>
>>
>> --
>>
>> DaveA
>>
>
> I am using Python 2.7. I don't think range() can take large values.
> example:
> I took a = 1000000000000000000 (10^18); This is the max limit in a puzzle.
> python showed the following error :OverflowError: range() has too many items.
> I even tried using xrange(), I didn't solve the issue..
>   		 	   		

Presumably you tried something like range(a), in which case you tried to 
create a list of 10**18 items, which is clearly too large for memory. 
But range(a, a+1000)  would be perfectly fine.  So it's not a case of 
range not accepting large values, but merely a question of how much will 
fit in memory.

As I said, just write your own generator to replace xrange, and you're 
fine.  You haven't said yet what you plan to do with it, but if you just 
want a generator for consecutive integers, you can use (untested)

def myrange(a, b):
     while a < b:
	yield a
         a += 1

It's not quite as flexible as xrange, nor as fast, but it's easy to type.

By the way, if you're evaluating some useful function for a few 
quadrillion items, running out of memory will be the least of your 
worries.  Usually, when the assignment involves huge numbers, there's a 
better approach than starting from zero.



-- 

DaveA

From shreeshbhat90 at gmail.com  Mon Jan 23 14:13:50 2012
From: shreeshbhat90 at gmail.com (Shreesh bhat)
Date: Mon, 23 Jan 2012 18:43:50 +0530
Subject: [Tutor] OverflowError in lucky numbers script
Message-ID: <CA+XJMJ6=UmrTS6x1SYbAzZ93gNd3aN-VUfiFAz44GLVgz1cocw@mail.gmail.com>

I tried optimizing everything all things you guys pointed out and still its
orders of magnitude away from the expected result.
The program should check the islucky condition between range of (1,10**18)
numbers and iterate over that 10**5 times.
This program slows down more than 16 secs at (1,10**8) and 1 time.
Which approach should i follow?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120123/8ee0345f/attachment.html>

From __peter__ at web.de  Mon Jan 23 14:44:08 2012
From: __peter__ at web.de (Peter Otten)
Date: Mon, 23 Jan 2012 14:44:08 +0100
Subject: [Tutor] OverflowError in lucky numbers script
References: <CA+XJMJ6=UmrTS6x1SYbAzZ93gNd3aN-VUfiFAz44GLVgz1cocw@mail.gmail.com>
Message-ID: <jfjo6u$bj7$1@dough.gmane.org>

Shreesh bhat wrote:

> I tried optimizing everything all things you guys pointed out and still
> its orders of magnitude away from the expected result.
> The program should check the islucky condition between range of (1,10**18)
> numbers and iterate over that 10**5 times.
> This program slows down more than 16 secs at (1,10**8) and 1 time.
> Which approach should i follow?

Consult the person who gave you this task -- there is no way python can even 
count to 10**18 in 16 seconds.


From steve at pearwood.info  Mon Jan 23 15:03:21 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 24 Jan 2012 01:03:21 +1100
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <CA+XJMJ6=UmrTS6x1SYbAzZ93gNd3aN-VUfiFAz44GLVgz1cocw@mail.gmail.com>
References: <CA+XJMJ6=UmrTS6x1SYbAzZ93gNd3aN-VUfiFAz44GLVgz1cocw@mail.gmail.com>
Message-ID: <20120123140321.GA6693@ando>

On Mon, Jan 23, 2012 at 06:43:50PM +0530, Shreesh bhat wrote:

> The program should check the islucky condition between range of (1,10**18)
> numbers and iterate over that 10**5 times.

How is the islucky condition defined?

The only version I have found is based on something quite similar to 
primes, where you start by writing all the numbers down:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ...

Then delete every second number:

1   3   5   7   9    11    13    15    17    ...

Now the next lowest number is 3, so delete every third number:

1   3       7   9          13    15          ...

The next survivor is 7, so delete every seventh number, and so on. The 
first few lucky numbers by this definition are:

1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 49, 51, 63, 67, 
69, 73, 75, 79, 87, 93, 99, ... (sequence A000959 in OEIS).

(See also the Wikipedia article on Lucky Numbers.) 

Is this the same definition of "lucky number" that your puzzle uses? If 
so, you will need to think about a clever way to test which numbers are 
lucky.

Quite frankly, if this is the definition of lucky numbers you are 
supposed to use, the only possible way you can calculate all the lucky 
numbers between 1 and 10**18, not once, but 10**5 times, in sixteen 
seconds, is to find some incredibly clever algorithm. Given the 
straight-forward algorithm above, I don't believe any supercomputer on 
earth could solve the problem as given.

Perhaps I have misunderstood the problem. Is it explained on some 
website?


-- 
Steven


From alan.gauld at btinternet.com  Mon Jan 23 19:20:15 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 23 Jan 2012 18:20:15 +0000
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <CA+XJMJ6=UmrTS6x1SYbAzZ93gNd3aN-VUfiFAz44GLVgz1cocw@mail.gmail.com>
References: <CA+XJMJ6=UmrTS6x1SYbAzZ93gNd3aN-VUfiFAz44GLVgz1cocw@mail.gmail.com>
Message-ID: <jfk8cv$fsn$1@dough.gmane.org>

On 23/01/12 13:13, Shreesh bhat wrote:
> I tried optimizing everything all things you guys pointed out and still
> its orders of magnitude away from the expected result.

That's what I suspected. It means the fundamental approach of testing 
every number can probably never work.

> Which approach should I follow?

You will need to go back to the math.
Find a better algorithm than testing all numbers. Maybe
you can find a way to generate the numbers rather than
eliminate them?

This may be a problem somebody else has solved so a Google/Wikipedia 
search may turn up some useful algorithms?

Since it seems to be a homework type assignment it would be normal
for it to be related to your classwork. So what have you been studying 
recently that might help?

One thing that might help is to generate all the primes you need in 
advance? For example if the max number is 10**18 that implies 18 digits, 
so the the max of the squares sum can only be 18*(9*9)=1458. Rather than 
checking for primeness it might be faster to calculate all primes up to 
that value and test for inclusion in that set.
Similarly the primes for addition are max 18*9 = 162, a very small set 
of primes...

Just a random thought, I have no idea how much that would help, if at 
all!...

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


From d at davea.name  Mon Jan 23 19:37:10 2012
From: d at davea.name (Dave Angel)
Date: Mon, 23 Jan 2012 13:37:10 -0500
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <jfk8cv$fsn$1@dough.gmane.org>
References: <CA+XJMJ6=UmrTS6x1SYbAzZ93gNd3aN-VUfiFAz44GLVgz1cocw@mail.gmail.com>
	<jfk8cv$fsn$1@dough.gmane.org>
Message-ID: <4F1DA8D6.5020103@davea.name>

On 01/23/2012 01:20 PM, Alan Gauld wrote:
> On 23/01/12 13:13, Shreesh bhat wrote:
>> I tried optimizing everything all things you guys pointed out and still
>> its orders of magnitude away from the expected result.
>
> That's what I suspected. It means the fundamental approach of testing 
> every number can probably never work.
>
>> Which approach should I follow?
>
> You will need to go back to the math.
> Find a better algorithm than testing all numbers. Maybe
> you can find a way to generate the numbers rather than
> eliminate them?
>
> This may be a problem somebody else has solved so a Google/Wikipedia 
> search may turn up some useful algorithms?
>
> Since it seems to be a homework type assignment it would be normal
> for it to be related to your classwork. So what have you been studying 
> recently that might help?
>
> One thing that might help is to generate all the primes you need in 
> advance? For example if the max number is 10**18 that implies 18 
> digits, so the the max of the squares sum can only be 18*(9*9)=1458. 
> Rather than checking for primeness it might be faster to calculate all 
> primes up to that value and test for inclusion in that set.
> Similarly the primes for addition are max 18*9 = 162, a very small set 
> of primes...
>
> Just a random thought, I have no idea how much that would help, if at 
> all!...
>
I already suggested that, and he already implemented it. Although it was 
inefficient, it was good enough and not the bottleneck.



-- 

DaveA


From d at davea.name  Mon Jan 23 19:42:19 2012
From: d at davea.name (Dave Angel)
Date: Mon, 23 Jan 2012 13:42:19 -0500
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <4F1DA522.4000306@dejaviewphoto.com>
References: <CA+XJMJ6=UmrTS6x1SYbAzZ93gNd3aN-VUfiFAz44GLVgz1cocw@mail.gmail.com>
	<4F1DA522.4000306@dejaviewphoto.com>
Message-ID: <4F1DAA0B.2060503@davea.name>

On 01/23/2012 08:13 AM, Shreesh bhat wrote:
> I tried optimizing everything all things you guys pointed out and 
> still its
> orders of magnitude away from the expected result.
> The program should check the islucky condition between range of 
> (1,10**18)
> numbers and iterate over that 10**5 times.
> This program slows down more than 16 secs at (1,10**8) and 1 time.
> Which approach should i follow?
>
>
You said the two end points of the range were less than 10**18, but I 
didn't realize you really wanted to do the entire range, meaning first 
number is 1 and last is 10**18.  To do that 100,000 times in 10 secs 
would mean you have to process 10**12 items per CPU clock cycle.

That's so far beyond possible that it's clear another approach is 
necessary.

If you're literally going to do all the possible 18 digit numbers, then 
perhaps you should be doing a combinational approach.  For example, once 
you know whether 38 is lucky, you also know whether 83, 380, 300008000, 
and 80030 are lucky.  So you test all possible ordered strings the way 
you're doing it now, and multiply each (0 or 1) by the number of ways 
those digits could be permuted in an 18 digit space (adding zeroes in 
various places, and of course reordering numbers).

So we're looking for a bunch of lists of 18 ints, where each of the int 
is between 0 and 9, and with a further constraint that the digits 
increase in a non-strict monatonic way.  You could do that with an 18 
level nested for-loop, or you could do it with recursion.  Anyway, the 
number of total loops changes from 10**18 to something more manageable, 
basically a time roughty factorial complexity.

Once you've written that set of loops (prob. done with recursion, so it 
can do a variable-sized list), you need a function that tests "is-lucky" 
and another that calculates the number of permutations of that 
particular combinations of terms.

DaveA

-- 

DaveA


From shreeshbhat90 at gmail.com  Mon Jan 23 19:51:04 2012
From: shreeshbhat90 at gmail.com (Shreesh bhat)
Date: Tue, 24 Jan 2012 00:21:04 +0530
Subject: [Tutor] OverflowError in lucky numbers script
Message-ID: <CA+XJMJ6wS-JR7F6ANND4Qk3HHVAsRMAG15n08sx7Mzbtwd8bmA@mail.gmail.com>

I have given the definition of lucky numbers and constraints involved at
the starting of the thread.
when a number's sum of digits and square of sum of digits is prime,it is
called lucky.

I already tried generating prime numbers using sieve of atkin algorithm
rather than doing primality test.
Efficiency improved a lot but still couldnt reach 16 sec target.

The large numbers are the only hindrance to the speed.
Since i m new to Python.I dont know all its recipes and tricks inlvolved to
"charm-the-snake".
So can i improve the islucky method more than what i mentioned before?
Can i work around that way in python or should i come up with a new
algorithm?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120124/2bb9e449/attachment.html>

From marc.tompkins at gmail.com  Mon Jan 23 20:42:08 2012
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 23 Jan 2012 11:42:08 -0800
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <CA+XJMJ6wS-JR7F6ANND4Qk3HHVAsRMAG15n08sx7Mzbtwd8bmA@mail.gmail.com>
References: <CA+XJMJ6wS-JR7F6ANND4Qk3HHVAsRMAG15n08sx7Mzbtwd8bmA@mail.gmail.com>
Message-ID: <CAKK8jXbvCgOLwXK5+HneSLEDHWjLmAJUi-bAjdVyFJ70xAMXiQ@mail.gmail.com>

On Mon, Jan 23, 2012 at 10:51 AM, Shreesh bhat <shreeshbhat90 at gmail.com>wrote:

> I have given the definition of lucky numbers and constraints involved at
> the starting of the thread.
> when a number's sum of digits and square of sum of digits is prime,it is
> called lucky.
>

Just to clarify: do you mean "(sum of digits) + (sum of digits)^2"?
If so, the ONLY lucky numbers are those whose digits add up to 1... because
"x + x^2" is always even (for real integers), and 2 is the only even prime
number.
So, if I understood your definition, here are the lucky numbers up to 10^18:
1
10
100
1000
...
10000000000000000
100000000000000000
1000000000000000000

It seems to me that the problem can't possibly be that simple, so I must
have misunderstood your definition.  Please explain!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120123/5b10e0d5/attachment.html>

From marc.tompkins at gmail.com  Mon Jan 23 20:45:57 2012
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 23 Jan 2012 11:45:57 -0800
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <CAKK8jXbvCgOLwXK5+HneSLEDHWjLmAJUi-bAjdVyFJ70xAMXiQ@mail.gmail.com>
References: <CA+XJMJ6wS-JR7F6ANND4Qk3HHVAsRMAG15n08sx7Mzbtwd8bmA@mail.gmail.com>
	<CAKK8jXbvCgOLwXK5+HneSLEDHWjLmAJUi-bAjdVyFJ70xAMXiQ@mail.gmail.com>
Message-ID: <CAKK8jXaN9DQco2gR2=egkGWhN-RbqsCTafBEO0KuxKYdmNPKJQ@mail.gmail.com>

On Mon, Jan 23, 2012 at 11:42 AM, Marc Tompkins <marc.tompkins at gmail.com>wrote:

> On Mon, Jan 23, 2012 at 10:51 AM, Shreesh bhat <shreeshbhat90 at gmail.com>wrote:
>
>> I have given the definition of lucky numbers and constraints involved at
>> the starting of the thread.
>> when a number's sum of digits and square of sum of digits is prime,it is
>> called lucky.
>>
>
>
I suspect, however, you might have meant THESE lucky numbers:
http://en.wikipedia.org/wiki/Lucky_number
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120123/eaaf919b/attachment.html>

From shreeshbhat90 at gmail.com  Mon Jan 23 21:08:49 2012
From: shreeshbhat90 at gmail.com (Shreesh bhat)
Date: Tue, 24 Jan 2012 01:38:49 +0530
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <CAKK8jXaN9DQco2gR2=egkGWhN-RbqsCTafBEO0KuxKYdmNPKJQ@mail.gmail.com>
References: <CA+XJMJ6wS-JR7F6ANND4Qk3HHVAsRMAG15n08sx7Mzbtwd8bmA@mail.gmail.com>
	<CAKK8jXbvCgOLwXK5+HneSLEDHWjLmAJUi-bAjdVyFJ70xAMXiQ@mail.gmail.com>
	<CAKK8jXaN9DQco2gR2=egkGWhN-RbqsCTafBEO0KuxKYdmNPKJQ@mail.gmail.com>
Message-ID: <CA+XJMJ4A_MQ=ugEXrk_3yowAUUusQ-xc77y1aLOfAUSmsWMysg@mail.gmail.com>

No,i meant sum of digits is prime and also sum of square of digits is prime.
E.g: 23 is lucky cos
2+3=>5 (prime)
2**2+3**2 => 4+9 => 13 (prime)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120124/d300442e/attachment.html>

From alan.gauld at btinternet.com  Mon Jan 23 23:01:33 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 23 Jan 2012 22:01:33 +0000
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <CA+XJMJ6wS-JR7F6ANND4Qk3HHVAsRMAG15n08sx7Mzbtwd8bmA@mail.gmail.com>
References: <CA+XJMJ6wS-JR7F6ANND4Qk3HHVAsRMAG15n08sx7Mzbtwd8bmA@mail.gmail.com>
Message-ID: <jfklbu$ibb$1@dough.gmane.org>

On 23/01/12 18:51, Shreesh bhat wrote:

> Since i m new to Python.I dont know all its recipes and tricks inlvolved
> to "charm-the-snake".
> So can i improve the islucky method more than what i mentioned before?

Not by enough to meet your constraints.

Just to be clear this has nothing to do with Python. It doesn't matter 
what programming language you choose there is not a PC on Earth that can 
do what you want using the technique you are using in 16 seconds.

> Can i work around that way in python or should i come up with a new
> algorithm?

You definitely need a fundamentally different algorithm.

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


From steve at pearwood.info  Mon Jan 23 23:55:50 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 24 Jan 2012 09:55:50 +1100
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <jfklbu$ibb$1@dough.gmane.org>
References: <CA+XJMJ6wS-JR7F6ANND4Qk3HHVAsRMAG15n08sx7Mzbtwd8bmA@mail.gmail.com>
	<jfklbu$ibb$1@dough.gmane.org>
Message-ID: <20120123225550.GB6693@ando>

On Mon, Jan 23, 2012 at 10:01:33PM +0000, Alan Gauld wrote:

> Just to be clear this has nothing to do with Python. It doesn't matter 
> what programming language you choose there is not a PC on Earth that can 
> do what you want using the technique you are using in 16 seconds.

I don't believe that you could do it with the fastest supercomputer on 
earth. If you have to test 10**18 numbers in 16/10**5 seconds, that 
gives you less than 0.0000000000002 nanoseconds per test.

This isn't a question of tweaking the code to make it run faster, you 
need a fundamentally different approach to the problem, as Alan says. 
Either that, or we have completely misunderstood the constraints of the 
puzzle.
 
> >Can i work around that way in python or should i come up with a new
> >algorithm?
> 
> You definitely need a fundamentally different algorithm.

I expect that this is some question from one of those annoying 
websites that offer extremely advanced mathematics puzzles disguised as 
a programming challenge. (Well I find them annoying. The answer almost 
always turns out to be something which took a genius of the level of 
Euler or Gauss to discover, and they expect you to come up with the 
answer on your own.)


-- 
Steven


From wprins at gmail.com  Tue Jan 24 00:26:30 2012
From: wprins at gmail.com (Walter Prins)
Date: Mon, 23 Jan 2012 23:26:30 +0000
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <20120123225550.GB6693@ando>
References: <CA+XJMJ6wS-JR7F6ANND4Qk3HHVAsRMAG15n08sx7Mzbtwd8bmA@mail.gmail.com>
	<jfklbu$ibb$1@dough.gmane.org> <20120123225550.GB6693@ando>
Message-ID: <CANLXbfBi1CdYgrfN9L510bXOnDpW_vkd2pA63Xk3fL=6dV8u8Q@mail.gmail.com>

Hi

On 23 January 2012 22:55, Steven D'Aprano <steve at pearwood.info> wrote:
>
>
> > >Can i work around that way in python or should i come up with a new
> > >algorithm?
> >
> > You definitely need a fundamentally different algorithm.
>
> I expect that this is some question from one of those annoying
> websites that offer extremely advanced mathematics puzzles disguised as
> a programming challenge. (Well I find them annoying. The answer almost
> always turns out to be something which took a genius of the level of
> Euler or Gauss to discover, and they expect you to come up with the
> answer on your own.)
>

The OP previously posted the question, and having reread it I think
perhaps he's too fixated on the maximum possible range in the
spec/question which gives rise to an practically impossible
computational burden.   To be precise, I think trying to feed A=1 and
B=10^18 seems to me to be asinine given that the the example test
cases given in the problem statement uses values of A and B that are
a) relatively small and b) quite close together.  That therefore gives
me the impression that being able to calculate all the answers for the
whole 1...10^18 range is rather not expected.  (The very fact that you
need to specify a sub-range within which to calculate the lucky
numbers in, implies that it's not expected, actually.)

Anyway, for reference I post the original question again:

> *Lucky Numbers*
> A number is called lucky if the sum of its digits, as well as the sum of
> the squares of its digits is a prime number. How many numbers between A
> and B are lucky?
> Input:
> The first line contains the number of test cases T. Each of the next T
> lines contains two integers, A and B.
> Output:
> Output T lines, one for each case containing the required answer for the
> corresponding case.
>
> Constraints:
> 1 <= T <= 10000
> 1 <= A <= B <= 10^18
> Sample Input:
> 2
> 1 20
> 120 130
> Sample Output:
> 4
> 1
> Explanation:
> For the first case, the lucky numbers are 11, 12, 14, 16.
> For the second case, the only lucky number is 120.

Walter

From marc.tompkins at gmail.com  Tue Jan 24 04:31:21 2012
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 23 Jan 2012 19:31:21 -0800
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <CA+XJMJ4A_MQ=ugEXrk_3yowAUUusQ-xc77y1aLOfAUSmsWMysg@mail.gmail.com>
References: <CA+XJMJ6wS-JR7F6ANND4Qk3HHVAsRMAG15n08sx7Mzbtwd8bmA@mail.gmail.com>
	<CAKK8jXbvCgOLwXK5+HneSLEDHWjLmAJUi-bAjdVyFJ70xAMXiQ@mail.gmail.com>
	<CAKK8jXaN9DQco2gR2=egkGWhN-RbqsCTafBEO0KuxKYdmNPKJQ@mail.gmail.com>
	<CA+XJMJ4A_MQ=ugEXrk_3yowAUUusQ-xc77y1aLOfAUSmsWMysg@mail.gmail.com>
Message-ID: <CAKK8jXYEsNjdn6uBQeiQ=rZWKYYYTssrL2GLEZ=UxE0qNSyZAQ@mail.gmail.com>

On Mon, Jan 23, 2012 at 12:08 PM, Shreesh bhat <shreeshbhat90 at gmail.com>wrote:

> No,i meant sum of digits is prime and also sum of square of digits is
> prime.
> E.g: 23 is lucky cos
> 2+3=>5 (prime)
> 2**2+3**2 => 4+9 => 13 (prime)
>

Thanks for the clarification - or I should say "correction", since "sum of
square of digits" and "square of sum of digits" are NOT equivalent!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120123/02e935e1/attachment.html>

From d at davea.name  Tue Jan 24 05:03:00 2012
From: d at davea.name (Dave Angel)
Date: Mon, 23 Jan 2012 23:03:00 -0500
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <CAKK8jXYEsNjdn6uBQeiQ=rZWKYYYTssrL2GLEZ=UxE0qNSyZAQ@mail.gmail.com>
References: <CA+XJMJ6wS-JR7F6ANND4Qk3HHVAsRMAG15n08sx7Mzbtwd8bmA@mail.gmail.com>	<CAKK8jXbvCgOLwXK5+HneSLEDHWjLmAJUi-bAjdVyFJ70xAMXiQ@mail.gmail.com>	<CAKK8jXaN9DQco2gR2=egkGWhN-RbqsCTafBEO0KuxKYdmNPKJQ@mail.gmail.com>	<CA+XJMJ4A_MQ=ugEXrk_3yowAUUusQ-xc77y1aLOfAUSmsWMysg@mail.gmail.com>
	<CAKK8jXYEsNjdn6uBQeiQ=rZWKYYYTssrL2GLEZ=UxE0qNSyZAQ@mail.gmail.com>
Message-ID: <4F1E2D74.705@davea.name>

On 01/23/2012 10:31 PM, Marc Tompkins wrote:
> On Mon, Jan 23, 2012 at 12:08 PM, Shreesh bhat<shreeshbhat90 at gmail.com>wrote:
>
>> No,i meant sum of digits is prime and also sum of square of digits is
>> prime.
>> E.g: 23 is lucky cos
>> 2+3=>5 (prime)
>> 2**2+3**2 =>  4+9 =>  13 (prime)
>>
> Thanks for the clarification - or I should say "correction", since "sum of
> square of digits" and "square of sum of digits" are NOT equivalent!
>
But Shreesh' original wording was:

A number is called lucky if the sum of its digits, as well as the sum of
the squares of its digits is a prime number. How many numbers between A and
B are lucky?

in a message 1/22/12 at 1:11, subject: "Re: [Tutor] Tutor Digest, Vol 
95, Issue 55"

That thread soon got renamed to "OverflowError in lucky numbers script"

-- 

DaveA


From marc.tompkins at gmail.com  Tue Jan 24 05:28:45 2012
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 23 Jan 2012 20:28:45 -0800
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <4F1E2D74.705@davea.name>
References: <CA+XJMJ6wS-JR7F6ANND4Qk3HHVAsRMAG15n08sx7Mzbtwd8bmA@mail.gmail.com>
	<CAKK8jXbvCgOLwXK5+HneSLEDHWjLmAJUi-bAjdVyFJ70xAMXiQ@mail.gmail.com>
	<CAKK8jXaN9DQco2gR2=egkGWhN-RbqsCTafBEO0KuxKYdmNPKJQ@mail.gmail.com>
	<CA+XJMJ4A_MQ=ugEXrk_3yowAUUusQ-xc77y1aLOfAUSmsWMysg@mail.gmail.com>
	<CAKK8jXYEsNjdn6uBQeiQ=rZWKYYYTssrL2GLEZ=UxE0qNSyZAQ@mail.gmail.com>
	<4F1E2D74.705@davea.name>
Message-ID: <CAKK8jXbPm7md+R81TOt9KxEptMrRNQN0pXYZhw6miob3YEnNow@mail.gmail.com>

On Mon, Jan 23, 2012 at 8:03 PM, Dave Angel <d at davea.name> wrote:

> On 01/23/2012 10:31 PM, Marc Tompkins wrote:
>
>> On Mon, Jan 23, 2012 at 12:08 PM, Shreesh bhat<shreeshbhat90 at gmail.com>**
>> wrote:
>>
>>  No,i meant sum of digits is prime and also sum of square of digits is
>>> prime.
>>> E.g: 23 is lucky cos
>>> 2+3=>5 (prime)
>>> 2**2+3**2 =>  4+9 =>  13 (prime)
>>>
>>>  Thanks for the clarification - or I should say "correction", since "sum
>> of
>> square of digits" and "square of sum of digits" are NOT equivalent!
>>
>>  But Shreesh' original wording was:
>
>
> A number is called lucky if the sum of its digits, as well as the sum of
> the squares of its digits is a prime number. How many numbers between A and
> B are lucky?
>
> in a message 1/22/12 at 1:11, subject: "Re: [Tutor] Tutor Digest, Vol 95,
> Issue 55"
>
> That thread soon got renamed to "OverflowError in lucky numbers script"
>
> Yes, but I - and apparently others - missed that thread; someone (Steven
D'Aprano?) asked for a re-statement of the problem; the re-statement (which
was the first time I'd seen the problem definition) was confusing.  Sorry
for starting a false trail; sorry for jumping in late.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120123/af25a1a3/attachment.html>

From d at davea.name  Tue Jan 24 07:45:08 2012
From: d at davea.name (Dave Angel)
Date: Tue, 24 Jan 2012 01:45:08 -0500
Subject: [Tutor] OverflowError in lucky numbers script
In-Reply-To: <20120123225550.GB6693@ando>
References: <CA+XJMJ6wS-JR7F6ANND4Qk3HHVAsRMAG15n08sx7Mzbtwd8bmA@mail.gmail.com>	<jfklbu$ibb$1@dough.gmane.org>
	<20120123225550.GB6693@ando>
Message-ID: <4F1E5374.7060301@davea.name>

On 01/23/2012 05:55 PM, Steven D'Aprano wrote:
> On Mon, Jan 23, 2012 at 10:01:33PM +0000, Alan Gauld wrote:
>
>> Just to be clear this has nothing to do with Python. It doesn't matter
>> what programming language you choose there is not a PC on Earth that can
>> do what you want using the technique you are using in 16 seconds.
> I don't believe that you could do it with the fastest supercomputer on
> earth. If you have to test 10**18 numbers in 16/10**5 seconds, that
> gives you less than 0.0000000000002 nanoseconds per test.
>
> This isn't a question of tweaking the code to make it run faster, you
> need a fundamentally different approach to the problem, as Alan says.
> Either that, or we have completely misunderstood the constraints of the
> puzzle.
I gave such an example approach, at 1:42 (actually, much earlier, but I 
forgot to change my send-from field, so Tutor bounced my message).  You 
can search for the message using the string  "to do all the possible 18 
digit numbers".

I can solve the problem of finding how many lucky numbers in the entire 
range 1 through 10**18 in a reasonable time.  I haven't coded the entire 
algorithm, but most of it exists, and takes 97 seconds for generating 
and testing for luckiness the 4,686,824 possible distinct sets of 
digits.  Thus my outer loop goes around 4.6 million times, rather than 
10**18 times.  Incidentally, I made the 18 an argument to main(), so 
it's easy to test on smaller values.

What I generate are all possible lists of digits, all of length 18,  in 
which the digits are in sorted order.  All that remains is multiplying 
the 1 or 0 for each of these 4.7 million lists by a 
number-of-permutations figure, which shouldn't be too hard to get.  It 
would trivially be 18 factorial, except that there are variable numbers 
of duplicates among those 18 digits.  Anyway, I claim that it won't add 
more than a few percent to finish the task.  Call it 100 seconds.  lots 
more than the 16 seconds originally specified for doing it 10,000 
times.  There are undoubtedly ways to optimize my code;  I made no real 
attempt to be optimal.  I just was worried about the algorithm.

Only catch is that we might not want all 10**18 numbers.  If we want a 
few million of them, all around 10**17, the original approach will work 
fine.  And if we want them all, my approach will work.  I haven't come 
up with a way to generalize either for things like "solve it for the 
range 1234567890123456 through twice that value".


-- 

DaveA


From nitcoolish at gmail.com  Wed Jan 25 10:46:05 2012
From: nitcoolish at gmail.com (Nitish Mahajan)
Date: Wed, 25 Jan 2012 15:16:05 +0530
Subject: [Tutor] P4Python silent Installation
Message-ID: <CADoM_dZQYm-5a3qn2nRf_xC6C73+ADQ_QtjQr+gGPXkFUB_cTQ@mail.gmail.com>

Hi,


I use Python 2.5 and hence consequently use the file
P4Python-1.0.win32-py2.5.exe in order to add the Perforce APIs. I would
like to create a silent installation for them.

Python 2.5 being an msi is easily run silently using /q but the other file
?P4Python-1.0.win32-py2.5.exe? doesnot accept that flag. It says that it is
created using ?Distutils-2.5.0?.

Is there any standard flag for silent installation for disutils file. Else
is there a way I can create an msi package of this file
?P4Python-1.0.win32-py2.5.exe? on which I can use the flag.



*Regards*,
Nitish
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120125/403b199b/attachment.html>

From steve at pearwood.info  Wed Jan 25 12:25:42 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 25 Jan 2012 22:25:42 +1100
Subject: [Tutor] P4Python silent Installation
In-Reply-To: <CADoM_dZQYm-5a3qn2nRf_xC6C73+ADQ_QtjQr+gGPXkFUB_cTQ@mail.gmail.com>
References: <CADoM_dZQYm-5a3qn2nRf_xC6C73+ADQ_QtjQr+gGPXkFUB_cTQ@mail.gmail.com>
Message-ID: <4F1FE6B6.9020500@pearwood.info>

Nitish Mahajan wrote:

> I use Python 2.5 and hence consequently use the file
> P4Python-1.0.win32-py2.5.exe in order to add the Perforce APIs. I would
> like to create a silent installation for them.


Hello Nitish,

This mailing list is for people interested in learning the language Python, 
not for arbitrary questions related to Python programming. Questions about 
writing silent installers using distutils are a bit too specialised for this list.

You might be lucky to find somebody who is expect on distutils here, but you 
are probably better off asking on a specialist distutils mailing list (if 
there is one) or perhaps the generic Python newsgroup comp.lang.python (also 
available as a mailing list, python-list at python.org).

Good luck!




-- 
Steven


From krush1954 at yahoo.com  Wed Jan 25 13:19:15 2012
From: krush1954 at yahoo.com (ken brockman)
Date: Wed, 25 Jan 2012 04:19:15 -0800 (PST)
Subject: [Tutor] how to read and write to a file
Message-ID: <1327493955.63824.YahooMailNeo@web39306.mail.mud.yahoo.com>

I would like to write to and read from a file from python. I wanted to use the file to save input to the program in a list. I have been looking around and there seems to be several ways to go about it. I tried pickling, but am having an issue with it. What would be the correct way to accomplish this? I have tried?several?ways, but to no avail. I get no error msg. but the list isn't retaining the info.?Is pickling even the best way to do it.

file1 = open("ArtyKlikes.p", "ab") ?# likesList
file2 = open("ArtyDislikes.p", "ab") ?# dislikes

pickle.dump(likesList, file1)
pickle.dump(dislikeList, file2)

file1.close()
file2.close()

Any help would be greatly appreciated.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120125/1fbc48d5/attachment.html>

From rhettnaxel at gmail.com  Wed Jan 25 13:38:14 2012
From: rhettnaxel at gmail.com (Alexander)
Date: Wed, 25 Jan 2012 07:38:14 -0500
Subject: [Tutor] how to read and write to a file
In-Reply-To: <1327493955.63824.YahooMailNeo@web39306.mail.mud.yahoo.com>
References: <1327493955.63824.YahooMailNeo@web39306.mail.mud.yahoo.com>
Message-ID: <CANS6qmCnKe7QD0havRYj8YoZvB3vxY5rPowQdL2fD9-Kr=nJ3w@mail.gmail.com>

On Wed, Jan 25, 2012 at 7:19 AM, ken brockman <krush1954 at yahoo.com> wrote:

> I would like to write to and read from a file from python. I wanted to use
> the file to save input to the program in a list. I have been looking around
> and there seems to be several ways to go about it. I tried pickling, but am
> having an issue with it. What would be the correct way to accomplish this?
> I have tried several ways, but to no avail. I get no error msg. but the
> list isn't retaining the info. Is pickling even the best way to do it.
>
> file1 = open("ArtyKlikes.p", "ab")  # likesList
> file2 = open("ArtyDislikes.p", "ab")  # dislikes
>
> pickle.dump(likesList, file1)
> pickle.dump(dislikeList, file2)
>
> file1.close()
> file2.close()
>
> Any help would be greatly appreciated.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
Hi Ken. If you just want to read and write from a text file then you don't
need to pickle.
For example,
(the file info.txt exists)

>>>fh = open ( 'info.txt', 'w' )
>>>fh.write ( 'peter piper picked a pack of pickled peppers.' )
>>>fh.close()
>>>fr = open ( 'info.txt', 'r')
>>>fr.readline()
'peter piper picked a pack of pickled peppers.'
>>>fr.close()

or whatever.
But do you have a need to use pickling?
-- 
Alexander
7D9C597B
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120125/bca17c31/attachment.html>

From rhettnaxel at gmail.com  Wed Jan 25 15:14:09 2012
From: rhettnaxel at gmail.com (Alexander)
Date: Wed, 25 Jan 2012 09:14:09 -0500
Subject: [Tutor] how to read and write to a file
In-Reply-To: <1327498347.23324.YahooMailNeo@web39302.mail.mud.yahoo.com>
References: <1327493955.63824.YahooMailNeo@web39306.mail.mud.yahoo.com>
	<CANS6qmCnKe7QD0havRYj8YoZvB3vxY5rPowQdL2fD9-Kr=nJ3w@mail.gmail.com>
	<1327498347.23324.YahooMailNeo@web39302.mail.mud.yahoo.com>
Message-ID: <CANS6qmCcehiemj3Dc52J7vPsXaWhk7+vq2gseewKxhMoTA91Aw@mail.gmail.com>

On Wed, Jan 25, 2012 at 8:32 AM, ken brockman <krush1954 at yahoo.com> wrote:
>
>
> ________________________________
> From: Alexander <rhettnaxel at gmail.com>
> To: ken brockman <krush1954 at yahoo.com>
> Cc: "tutor at python.org" <tutor at python.org>
> Sent: Wednesday, January 25, 2012 7:38 AM
> Subject: Re: [Tutor] how to read and write to a file
>
>
>
> On Wed, Jan 25, 2012 at 7:19 AM, ken brockman <krush1954 at yahoo.com> wrote:
>
> I would like to write to and read from a file from python. I wanted to use the file to save input to the program in a list. I have been looking around and there seems to be several ways to go about it. I tried pickling, but am having an issue with it. What would be the correct way to accomplish this? I have tried?several?ways, but to no avail. I get no error msg. but the list isn't retaining the info.?Is pickling even the best way to do it.
>
> file1 = open("ArtyKlikes.p", "ab") ?# likesList
> file2 = open("ArtyDislikes.p", "ab") ?# dislikes
>
> pickle.dump(likesList, file1)
> pickle.dump(dislikeList, file2)
>
> file1.close()
> file2.close()
>
> Any help would be greatly appreciated.
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
> Hi Ken. If you just want to read and write from a text file then you don't need to pickle.
> For example,
> (the file info.txt exists)
>
> >>>fh = open ( 'info.txt', 'w' )
> >>>fh.write ( 'peter piper picked a pack of pickled peppers.' )
> >>>fh.close()
> >>>fr = open ( 'info.txt', 'r')
> >>>fr.readline()
> 'peter piper picked a pack of pickled peppers.'
> >>>fr.close()
>
> or whatever.
> But do you have a need to use pickling?
> --
> Alexander
> 7D9C597B
> --------------------------------------------------------------------------
>
> Hey Alexander,
> I had to try it before I went to sleep.
> No good. I got an error msg. TypeError: must be str, not list.
> So I guess that may be why i had went with pickling. I needed something that would work with a list. Unless there is some other way?
> Thanks again for taking the time to help out.
>
> Ken
>
>
Ken, pickling is used when one wants to send information through a
network or communicate with a database. Somebody else here knows more
about pickling than I do. As for your list problem... I'm not exactly
certain what you're trying to do. But I'm going with the idea that you
have two files of information, one contains strings you like, and the
other contains strings you dislike. And you want to read and write
this information using Python.

>>> like = [ 'orange', 'blue', 'red' ] #things I like
>>> dislike = [ 'apples', 'bronze', 'bananas' ] #things I dislike
>>> fh = open ( 'likes.txt', 'w' ) #let's open a file stream to write

# fh is my shorthand for "file handle"
#writing a list to a file stream:

>>> for index in range( len( like )):
fh.write( like[ index ] )
fh.write ( '\n' ) #here i add a new line, maybe somebody else
#knows a better way to avoid this?

>>> fh.close()

#now let's read that information into a list
>>> fr = open ( 'info.txt' ) #I'm using python 3.2
>>> mylistoflikes = fr.readlines()
>>> mylistoflikes
[ 'orange\n' , 'blue\n' , 'red\n' ]
>>> fr.close()

--
Alexander
7D9C597B

From joel.goldstick at gmail.com  Wed Jan 25 15:54:43 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Wed, 25 Jan 2012 09:54:43 -0500
Subject: [Tutor] how to read and write to a file
In-Reply-To: <CANS6qmCcehiemj3Dc52J7vPsXaWhk7+vq2gseewKxhMoTA91Aw@mail.gmail.com>
References: <1327493955.63824.YahooMailNeo@web39306.mail.mud.yahoo.com>
	<CANS6qmCnKe7QD0havRYj8YoZvB3vxY5rPowQdL2fD9-Kr=nJ3w@mail.gmail.com>
	<1327498347.23324.YahooMailNeo@web39302.mail.mud.yahoo.com>
	<CANS6qmCcehiemj3Dc52J7vPsXaWhk7+vq2gseewKxhMoTA91Aw@mail.gmail.com>
Message-ID: <CAPM-O+wEBPV_kXfrGoTfqtoiZW0FyZkzuGs8ZgdJWoca_goROg@mail.gmail.com>

On Wed, Jan 25, 2012 at 9:14 AM, Alexander <rhettnaxel at gmail.com> wrote:
> On Wed, Jan 25, 2012 at 8:32 AM, ken brockman <krush1954 at yahoo.com> wrote:
>>
>>
>> ________________________________
>> From: Alexander <rhettnaxel at gmail.com>
>> To: ken brockman <krush1954 at yahoo.com>
>> Cc: "tutor at python.org" <tutor at python.org>
>> Sent: Wednesday, January 25, 2012 7:38 AM
>> Subject: Re: [Tutor] how to read and write to a file
>>
>>
>>
>> On Wed, Jan 25, 2012 at 7:19 AM, ken brockman <krush1954 at yahoo.com> wrote:
>>
>> I would like to write to and read from a file from python. I wanted to use the file to save input to the program in a list. I have been looking around and there seems to be several ways to go about it. I tried pickling, but am having an issue with it. What would be the correct way to accomplish this? I have tried?several?ways, but to no avail. I get no error msg. but the list isn't retaining the info.?Is pickling even the best way to do it.
>>
>> file1 = open("ArtyKlikes.p", "ab") ?# likesList
>> file2 = open("ArtyDislikes.p", "ab") ?# dislikes
>>
>> pickle.dump(likesList, file1)
>> pickle.dump(dislikeList, file2)
>>
>> file1.close()
>> file2.close()
>>
>> Any help would be greatly appreciated.
>>
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>> Hi Ken. If you just want to read and write from a text file then you don't need to pickle.
>> For example,
>> (the file info.txt exists)
>>
>> >>>fh = open ( 'info.txt', 'w' )
>> >>>fh.write ( 'peter piper picked a pack of pickled peppers.' )
>> >>>fh.close()
>> >>>fr = open ( 'info.txt', 'r')
>> >>>fr.readline()
>> 'peter piper picked a pack of pickled peppers.'
>> >>>fr.close()
>>
>> or whatever.
>> But do you have a need to use pickling?
>> --
>> Alexander
>> 7D9C597B
>> --------------------------------------------------------------------------
>>
>> Hey Alexander,
>> I had to try it before I went to sleep.
>> No good. I got an error msg. TypeError: must be str, not list.
>> So I guess that may be why i had went with pickling. I needed something that would work with a list. Unless there is some other way?
>> Thanks again for taking the time to help out.
>>
>> Ken
>>
>>
> Ken, pickling is used when one wants to send information through a
> network or communicate with a database. Somebody else here knows more
> about pickling than I do. As for your list problem... I'm not exactly
> certain what you're trying to do. But I'm going with the idea that you
> have two files of information, one contains strings you like, and the
> other contains strings you dislike. And you want to read and write
> this information using Python.
>
>>>> like = [ 'orange', 'blue', 'red' ] #things I like
>>>> dislike = [ 'apples', 'bronze', 'bananas' ] #things I dislike
>>>> fh = open ( 'likes.txt', 'w' ) #let's open a file stream to write
>
> # fh is my shorthand for "file handle"
> #writing a list to a file stream:
>
>>>> for index in range( len( like )):
> fh.write( like[ index ] )
> fh.write ( '\n' ) #here i add a new line, maybe somebody else
> #knows a better way to avoid this?
>
>>>> fh.close()
>
> #now let's read that information into a list
>>>> fr = open ( 'info.txt' ) #I'm using python 3.2
>>>> mylistoflikes = fr.readlines()
>>>> mylistoflikes
> [ 'orange\n' , 'blue\n' , 'red\n' ]
>>>> fr.close()
>
> --
> Alexander
> 7D9C597B
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

First, pickle is used to store data objects.  If you just want to
store text, you just write it and read it back from your file.  But
there are situations where you want to save an object.  Maybe you want
to have it available to another program.

So, you nearly got through your example.  You pickled your lists, and
stored them, but you didn't retrieve them.

Here is a link to review: http://wiki.python.org/moin/UsingPickle

Here is my version of your program.  It worked for me.  copy and paste
it in a file, and try it
-----------------------------------------------
import pickle


ArtyKlikes = (1,2,3)
ArtyKDislikes = (4,5,6)

file1 = open("ArtyKlikes.p", "ab")  # likesList
file2 = open("ArtyDislikes.p", "ab")  # dislikes

pickle.dump(ArtyKlikes, file1)
pickle.dump(ArtyKDislikes, file2)

file1.close()
file2.close()

ArtyLikes = pickle.load(open("ArtyKlikes.p", 'rb'))
ArtyDisLikes = pickle.load(open("ArtyDislikes.p", 'rb'))

print ArtyLikes
print ArtyDisLikes

-- 
Joel Goldstick

From joel.goldstick at gmail.com  Wed Jan 25 17:04:43 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Wed, 25 Jan 2012 11:04:43 -0500
Subject: [Tutor] how to read and write to a file
In-Reply-To: <1327506625.57224.YahooMailNeo@web39306.mail.mud.yahoo.com>
References: <1327493955.63824.YahooMailNeo@web39306.mail.mud.yahoo.com>
	<CANS6qmCnKe7QD0havRYj8YoZvB3vxY5rPowQdL2fD9-Kr=nJ3w@mail.gmail.com>
	<1327498347.23324.YahooMailNeo@web39302.mail.mud.yahoo.com>
	<CANS6qmCcehiemj3Dc52J7vPsXaWhk7+vq2gseewKxhMoTA91Aw@mail.gmail.com>
	<CAPM-O+wEBPV_kXfrGoTfqtoiZW0FyZkzuGs8ZgdJWoca_goROg@mail.gmail.com>
	<1327506625.57224.YahooMailNeo@web39306.mail.mud.yahoo.com>
Message-ID: <CAPM-O+wA_Yrix3jiOe2Cqzsbqh-SBK2wbf6wxPT-9=VdWcpn9w@mail.gmail.com>

On Wed, Jan 25, 2012 at 10:50 AM, ken brockman <krush1954 at yahoo.com> wrote:
> Thank you Joel and Alexander for your time and input.
> I had just wanted to be able to store a list and read and write to it. But
> it seems reading and writing is no go with lists, only strings, or no? Is
> there a simply way I can tweak the read write feature to do lists? I'm sorry
> if I seem a tad slow on the uptick, I'm just starting to get
> into?programming?and being up all night is not helping my comprehension
> skills none. ?I've not as yet tried either of your suggestions, but from
> what I can gather pickling is not the right tool for the job at hand. I'm
> not looking to have it read by another program nor send it over a network.
>
> Also I have two lists and two files. Is it possible to store both lists in
> one file? I wouldn't?imagine you could, but?hey,?doesn't hurt to ask.
> Thanks again.
>
> Ken
>
> ________________________________
> From: Joel Goldstick <joel.goldstick at gmail.com>
> To: Alexander <rhettnaxel at gmail.com>
> Cc: ken brockman <krush1954 at yahoo.com>; tutor at python.org
> Sent: Wednesday, January 25, 2012 9:54 AM
>
> Subject: Re: [Tutor] how to read and write to a file
>
> On Wed, Jan 25, 2012 at 9:14 AM, Alexander <rhettnaxel at gmail.com> wrote:
>> On Wed, Jan 25, 2012 at 8:32 AM, ken brockman <krush1954 at yahoo.com> wrote:
>>>
>>>
>>> ________________________________
>>> From: Alexander <rhettnaxel at gmail.com>
>>> To: ken brockman <krush1954 at yahoo.com>
>>> Cc: "tutor at python.org" <tutor at python.org>
>>> Sent: Wednesday, January 25, 2012 7:38 AM
>>> Subject: Re: [Tutor] how to read and write to a file
>>>
>>>
>>>
>>> On Wed, Jan 25, 2012 at 7:19 AM, ken brockman <krush1954 at yahoo.com>
>>> wrote:
>>>
>>> I would like to write to and read from a file from python. I wanted to
>>> use the file to save input to the program in a list. I have been looking
>>> around and there seems to be several ways to go about it. I tried pickling,
>>> but am having an issue with it. What would be the correct way to accomplish
>>> this? I have tried?several?ways, but to no avail. I get no error msg. but
>>> the list isn't retaining the info.?Is pickling even the best way to do it.
>>>
>>> file1 = open("ArtyKlikes.p", "ab") ?# likesList
>>> file2 = open("ArtyDislikes.p", "ab") ?# dislikes
>>>
>>> pickle.dump(likesList, file1)
>>> pickle.dump(dislikeList, file2)
>>>
>>> file1.close()
>>> file2.close()
>>>
>>> Any help would be greatly appreciated.
>>>
>>> _______________________________________________
>>> Tutor maillist ?- ?Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>> Hi Ken. If you just want to read and write from a text file then you
>>> don't need to pickle.
>>> For example,
>>> (the file info.txt exists)
>>>
>>> >>>fh = open ( 'info.txt', 'w' )
>>> >>>fh.write ( 'peter piper picked a pack of pickled peppers.' )
>>> >>>fh.close()
>>> >>>fr = open ( 'info.txt', 'r')
>>> >>>fr.readline()
>>> 'peter piper picked a pack of pickled peppers.'
>>> >>>fr.close()
>>>
>>> or whatever.
>>> But do you have a need to use pickling?
>>> --
>>> Alexander
>>> 7D9C597B
>>>
>>> --------------------------------------------------------------------------
>>>
>>> Hey Alexander,
>>> I had to try it before I went to sleep.
>>> No good. I got an error msg. TypeError: must be str, not list.
>>> So I guess that may be why i had went with pickling. I needed something
>>> that would work with a list. Unless there is some other way?
>>> Thanks again for taking the time to help out.
>>>
>>> Ken
>>>
>>>
>> Ken, pickling is used when one wants to send information through a
>> network or communicate with a database. Somebody else here knows more
>> about pickling than I do. As for your list problem... I'm not exactly
>> certain what you're trying to do. But I'm going with the idea that you
>> have two files of information, one contains strings you like, and the
>> other contains strings you dislike. And you want to read and write
>> this information using Python.
>>
>>>>> like = [ 'orange', 'blue', 'red' ] #things I like
>>>>> dislike = [ 'apples', 'bronze', 'bananas' ] #things I dislike
>>>>> fh = open ( 'likes.txt', 'w' ) #let's open a file stream to write
>>
>> # fh is my shorthand for "file handle"
>> #writing a list to a file stream:
>>
>>>>> for index in range( len( like )):
>> fh.write( like[ index ] )
>> fh.write ( '\n' ) #here i add a new line, maybe somebody else
>> #knows a better way to avoid this?
>>
>>>>> fh.close()
>>
>> #now let's read that information into a list
>>>>> fr = open ( 'info.txt' ) #I'm using python 3.2
>>>>> mylistoflikes = fr.readlines()
>>>>> mylistoflikes
>> [ 'orange\n' , 'blue\n' , 'red\n' ]
>>>>> fr.close()
>>
>> --
>> Alexander
>> 7D9C597B
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> First, pickle is used to store data objects.? If you just want to
> store text, you just write it and read it back from your file.? But
> there are situations where you want to save an object.? Maybe you want
> to have it available to another program.
>
> So, you nearly got through your example.? You pickled your lists, and
> stored them, but you didn't retrieve them.
>
> Here is a link to review: http://wiki.python.org/moin/UsingPickle
>
> Here is my version of your program.? It worked for me.? copy and paste
> it in a file, and try it
> -----------------------------------------------
> import pickle
>
>
> ArtyKlikes = (1,2,3)
> ArtyKDislikes = (4,5,6)
>
> file1 = open("ArtyKlikes.p", "ab")? # likesList
> file2 = open("ArtyDislikes.p", "ab")? # dislikes
>
> pickle.dump(ArtyKlikes, file1)
> pickle.dump(ArtyKDislikes, file2)
>
> file1.close()
> file2.close()
>
> ArtyLikes = pickle.load(open("ArtyKlikes.p", 'rb'))
> ArtyDisLikes = pickle.load(open("ArtyDislikes.p", 'rb'))
>
> print ArtyLikes
> print ArtyDisLikes
>
> --
> Joel Goldstick
>
>
Ken,

First of all, always remember to reply to all on the list.  That keeps
everyone in the loop.
Second, don't 'top post'.  Write your comments at the end of the
thread so that people can follow the conversation.  Sometimes its
useful to intersperse comments in someone's previous email.

Writing text to a file and reading it is useful, and pretty easy to
understand.  But when you say you want to write a list you have to
start to understand what a list really is (or a dict or some other
object).  A list is not only the values in the list, it is also the
code that lets a list do what lists do.  Things like:

   for something in mylist:
       # do something with 'something'
or:
  print mylist[2]

and so on.

So, pickle is doing a whole lot more than writing '(1,2,3)' to your
file.  It knows it is a list and it stores all it needs to about the
list, including your specific list items.






-- 
Joel Goldstick

From krush1954 at yahoo.com  Wed Jan 25 17:30:50 2012
From: krush1954 at yahoo.com (ken brockman)
Date: Wed, 25 Jan 2012 08:30:50 -0800 (PST)
Subject: [Tutor] how to read and write to a file
In-Reply-To: <CAPM-O+wA_Yrix3jiOe2Cqzsbqh-SBK2wbf6wxPT-9=VdWcpn9w@mail.gmail.com>
References: <1327493955.63824.YahooMailNeo@web39306.mail.mud.yahoo.com>
	<CANS6qmCnKe7QD0havRYj8YoZvB3vxY5rPowQdL2fD9-Kr=nJ3w@mail.gmail.com>
	<1327498347.23324.YahooMailNeo@web39302.mail.mud.yahoo.com>
	<CANS6qmCcehiemj3Dc52J7vPsXaWhk7+vq2gseewKxhMoTA91Aw@mail.gmail.com>
	<CAPM-O+wEBPV_kXfrGoTfqtoiZW0FyZkzuGs8ZgdJWoca_goROg@mail.gmail.com>
	<1327506625.57224.YahooMailNeo@web39306.mail.mud.yahoo.com>
	<CAPM-O+wA_Yrix3jiOe2Cqzsbqh-SBK2wbf6wxPT-9=VdWcpn9w@mail.gmail.com>
Message-ID: <1327509050.61745.YahooMailNeo@web39302.mail.mud.yahoo.com>

Okay, got ya. Mea Culpa. 
Being misanthropic by nature I've not used or engaged  in a interactive forum such as this one before . 
I do grasp that a list is more then just the information it contains. So, does that mean i go with pickling? And can I save  two lists in one pickled file, or no?

Thanks one and all, for the help.
Ken


________________________________
 From: Joel Goldstick <joel.goldstick at gmail.com>
To: ken brockman <krush1954 at yahoo.com> 
Cc: tutor at python.org 
Sent: Wednesday, January 25, 2012 11:04 AM
Subject: Re: [Tutor] how to read and write to a file
 
On Wed, Jan 25, 2012 at 10:50 AM, ken brockman <krush1954 at yahoo.com> wrote:
> Thank you Joel and Alexander for your time and input.
> I had just wanted to be able to store a list and read and write to it. But
> it seems reading and writing is no go with lists, only strings, or no? Is
> there a simply way I can tweak the read write feature to do lists? I'm sorry
> if I seem a tad slow on the uptick, I'm just starting to get
> into?programming?and being up all night is not helping my comprehension
> skills none. ?I've not as yet tried either of your suggestions, but from
> what I can gather pickling is not the right tool for the job at hand. I'm
> not looking to have it read by another program nor send it over a network.
>
> Also I have two lists and two files. Is it possible to store both lists in
> one file? I wouldn't?imagine you could, but?hey,?doesn't hurt to ask.
> Thanks again.
>
> Ken
>
> ________________________________
> From: Joel Goldstick <joel.goldstick at gmail.com>
> To: Alexander <rhettnaxel at gmail.com>
> Cc: ken brockman <krush1954 at yahoo.com>; tutor at python.org
> Sent: Wednesday, January 25, 2012 9:54 AM
>
> Subject: Re: [Tutor] how to read and write to a file
>
> On Wed, Jan 25, 2012 at 9:14 AM, Alexander <rhettnaxel at gmail.com> wrote:
>> On Wed, Jan 25, 2012 at 8:32 AM, ken brockman <krush1954 at yahoo.com> wrote:
>>>
>>>
>>> ________________________________
>>> From: Alexander <rhettnaxel at gmail.com>
>>> To: ken brockman <krush1954 at yahoo.com>
>>> Cc: "tutor at python.org" <tutor at python.org>
>>> Sent: Wednesday, January 25, 2012 7:38 AM
>>> Subject: Re: [Tutor] how to read and write to a file
>>>
>>>
>>>
>>> On Wed, Jan 25, 2012 at 7:19 AM, ken brockman <krush1954 at yahoo.com>
>>> wrote:
>>>
>>> I would like to write to and read from a file from python. I wanted to
>>> use the file to save input to the program in a list. I have been looking
>>> around and there seems to be several ways to go about it. I tried pickling,
>>> but am having an issue with it. What would be the correct way to accomplish
>>> this? I have tried?several?ways, but to no avail. I get no error msg. but
>>> the list isn't retaining the info.?Is pickling even the best way to do it.
>>>
>>> file1 = open("ArtyKlikes.p", "ab") ?# likesList
>>> file2 = open("ArtyDislikes.p", "ab") ?# dislikes
>>>
>>> pickle.dump(likesList, file1)
>>> pickle.dump(dislikeList, file2)
>>>
>>> file1.close()
>>> file2.close()
>>>
>>> Any help would be greatly appreciated.
>>>
>>> _______________________________________________
>>> Tutor maillist ?- ?Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>> Hi Ken. If you just want to read and write from a text file then you
>>> don't need to pickle.
>>> For example,
>>> (the file info.txt exists)
>>>
>>> >>>fh = open ( 'info.txt', 'w' )
>>> >>>fh.write ( 'peter piper picked a pack of pickled peppers.' )
>>> >>>fh.close()
>>> >>>fr = open ( 'info.txt', 'r')
>>> >>>fr.readline()
>>> 'peter piper picked a pack of pickled peppers.'
>>> >>>fr.close()
>>>
>>> or whatever.
>>> But do you have a need to use pickling?
>>> --
>>> Alexander
>>> 7D9C597B
>>>
>>> --------------------------------------------------------------------------
>>>
>>> Hey Alexander,
>>> I had to try it before I went to sleep.
>>> No good. I got an error msg. TypeError: must be str, not list.
>>> So I guess that may be why i had went with pickling. I needed something
>>> that would work with a list. Unless there is some other way?
>>> Thanks again for taking the time to help out.
>>>
>>> Ken
>>>
>>>
>> Ken, pickling is used when one wants to send information through a
>> network or communicate with a database. Somebody else here knows more
>> about pickling than I do. As for your list problem... I'm not exactly
>> certain what you're trying to do. But I'm going with the idea that you
>> have two files of information, one contains strings you like, and the
>> other contains strings you dislike. And you want to read and write
>> this information using Python.
>>
>>>>> like = [ 'orange', 'blue', 'red' ] #things I like
>>>>> dislike = [ 'apples', 'bronze', 'bananas' ] #things I dislike
>>>>> fh = open ( 'likes.txt', 'w' ) #let's open a file stream to write
>>
>> # fh is my shorthand for "file handle"
>> #writing a list to a file stream:
>>
>>>>> for index in range( len( like )):
>> fh.write( like[ index ] )
>> fh.write ( '\n' ) #here i add a new line, maybe somebody else
>> #knows a better way to avoid this?
>>
>>>>> fh.close()
>>
>> #now let's read that information into a list
>>>>> fr = open ( 'info.txt' ) #I'm using python 3.2
>>>>> mylistoflikes = fr.readlines()
>>>>> mylistoflikes
>> [ 'orange\n' , 'blue\n' , 'red\n' ]
>>>>> fr.close()
>>
>> --
>> Alexander
>> 7D9C597B
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> First, pickle is used to store data objects.? If you just want to
> store text, you just write it and read it back from your file.? But
> there are situations where you want to save an object.? Maybe you want
> to have it available to another program.
>
> So, you nearly got through your example.? You pickled your lists, and
> stored them, but you didn't retrieve them.
>
> Here is a link to review: http://wiki.python.org/moin/UsingPickle
>
> Here is my version of your program.? It worked for me.? copy and paste
> it in a file, and try it
> -----------------------------------------------
> import pickle
>
>
> ArtyKlikes = (1,2,3)
> ArtyKDislikes = (4,5,6)
>
> file1 = open("ArtyKlikes.p", "ab")? # likesList
> file2 = open("ArtyDislikes.p", "ab")? # dislikes
>
> pickle.dump(ArtyKlikes, file1)
> pickle.dump(ArtyKDislikes, file2)
>
> file1.close()
> file2.close()
>
> ArtyLikes = pickle.load(open("ArtyKlikes.p", 'rb'))
> ArtyDisLikes = pickle.load(open("ArtyDislikes.p", 'rb'))
>
> print ArtyLikes
> print ArtyDisLikes
>
> --
> Joel Goldstick
>
>
Ken,

First of all, always remember to reply to all on the list.? That keeps
everyone in the loop.
Second, don't 'top post'.? Write your comments at the end of the
thread so that people can follow the conversation.? Sometimes its
useful to intersperse comments in someone's previous email.

Writing text to a file and reading it is useful, and pretty easy to
understand.? But when you say you want to write a list you have to
start to understand what a list really is (or a dict or some other
object).? A list is not only the values in the list, it is also the
code that lets a list do what lists do.? Things like:

?  for something in mylist:
? ? ?  # do something with 'something'
or:
? print mylist[2]

and so on.

So, pickle is doing a whole lot more than writing '(1,2,3)' to your
file.? It knows it is a list and it stores all it needs to about the
list, including your specific list items.






-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120125/70d7c6aa/attachment-0001.html>

From joel.goldstick at gmail.com  Wed Jan 25 18:00:32 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Wed, 25 Jan 2012 12:00:32 -0500
Subject: [Tutor] how to read and write to a file
In-Reply-To: <1327509050.61745.YahooMailNeo@web39302.mail.mud.yahoo.com>
References: <1327493955.63824.YahooMailNeo@web39306.mail.mud.yahoo.com>
	<CANS6qmCnKe7QD0havRYj8YoZvB3vxY5rPowQdL2fD9-Kr=nJ3w@mail.gmail.com>
	<1327498347.23324.YahooMailNeo@web39302.mail.mud.yahoo.com>
	<CANS6qmCcehiemj3Dc52J7vPsXaWhk7+vq2gseewKxhMoTA91Aw@mail.gmail.com>
	<CAPM-O+wEBPV_kXfrGoTfqtoiZW0FyZkzuGs8ZgdJWoca_goROg@mail.gmail.com>
	<1327506625.57224.YahooMailNeo@web39306.mail.mud.yahoo.com>
	<CAPM-O+wA_Yrix3jiOe2Cqzsbqh-SBK2wbf6wxPT-9=VdWcpn9w@mail.gmail.com>
	<1327509050.61745.YahooMailNeo@web39302.mail.mud.yahoo.com>
Message-ID: <CAPM-O+w_qpQ615N2ci2F7-LjY3FDRVUQE5o+hy7HmFeAWQrnSg@mail.gmail.com>

On Wed, Jan 25, 2012 at 11:30 AM, ken brockman <krush1954 at yahoo.com> wrote:
> Okay, got ya. Mea Culpa.
> Being misanthropic by nature I've not used or engaged??in a interactive
> forum such as this one before .
> I do grasp that a list is more then just the information it contains. So,
> does that mean i go with pickling? And can I save??two lists in one pickled
> file, or no?
>
> Thanks one and all, for the help.
> Ken
> ________________________________
> From: Joel Goldstick <joel.goldstick at gmail.com>
> To: ken brockman <krush1954 at yahoo.com>
> Cc: tutor at python.org
> Sent: Wednesday, January 25, 2012 11:04 AM
>
> Subject: Re: [Tutor] how to read and write to a file
>
> On Wed, Jan 25, 2012 at 10:50 AM, ken brockman <krush1954 at yahoo.com> wrote:
>> Thank you Joel and Alexander for your time and input.
>> I had just wanted to be able to store a list and read and write to it. But
>> it seems reading and writing is no go with lists, only strings, or no? Is
>> there a simply way I can tweak the read write feature to do lists? I'm
>> sorry
>> if I seem a tad slow on the uptick, I'm just starting to get
>> into?programming?and being up all night is not helping my comprehension
>> skills none. ?I've not as yet tried either of your suggestions, but from
>> what I can gather pickling is not the right tool for the job at hand. I'm
>> not looking to have it read by another program nor send it over a network.
>>
>> Also I have two lists and two files. Is it possible to store both lists in
>> one file? I wouldn't?imagine you could, but?hey,?doesn't hurt to ask.
>> Thanks again.
>>
>> Ken
>>
>> ________________________________
>> From: Joel Goldstick <joel.goldstick at gmail.com>
>> To: Alexander <rhettnaxel at gmail.com>
>> Cc: ken brockman <krush1954 at yahoo.com>; tutor at python.org
>> Sent: Wednesday, January 25, 2012 9:54 AM
>>
>> Subject: Re: [Tutor] how to read and write to a file
>>
>> On Wed, Jan 25, 2012 at 9:14 AM, Alexander <rhettnaxel at gmail.com> wrote:
>>> On Wed, Jan 25, 2012 at 8:32 AM, ken brockman <krush1954 at yahoo.com>
>>> wrote:
>>>>
>>>>
>>>> ________________________________
>>>> From: Alexander <rhettnaxel at gmail.com>
>>>> To: ken brockman <krush1954 at yahoo.com>
>>>> Cc: "tutor at python.org" <tutor at python.org>
>>>> Sent: Wednesday, January 25, 2012 7:38 AM
>>>> Subject: Re: [Tutor] how to read and write to a file
>>>>
>>>>
>>>>
>>>> On Wed, Jan 25, 2012 at 7:19 AM, ken brockman <krush1954 at yahoo.com>
>>>> wrote:
>>>>
>>>> I would like to write to and read from a file from python. I wanted to
>>>> use the file to save input to the program in a list. I have been looking
>>>> around and there seems to be several ways to go about it. I tried
>>>> pickling,
>>>> but am having an issue with it. What would be the correct way to
>>>> accomplish
>>>> this? I have tried?several?ways, but to no avail. I get no error msg.
>>>> but
>>>> the list isn't retaining the info.?Is pickling even the best way to do
>>>> it.
>>>>
>>>> file1 = open("ArtyKlikes.p", "ab") ?# likesList
>>>> file2 = open("ArtyDislikes.p", "ab") ?# dislikes
>>>>
>>>> pickle.dump(likesList, file1)
>>>> pickle.dump(dislikeList, file2)
>>>>
>>>> file1.close()
>>>> file2.close()
>>>>
>>>> Any help would be greatly appreciated.
>>>>
>>>> _______________________________________________
>>>> Tutor maillist ?- ?Tutor at python.org
>>>> To unsubscribe or change subscription options:
>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>
>>>>
>>>> Hi Ken. If you just want to read and write from a text file then you
>>>> don't need to pickle.
>>>> For example,
>>>> (the file info.txt exists)
>>>>
>>>> >>>fh = open ( 'info.txt', 'w' )
>>>> >>>fh.write ( 'peter piper picked a pack of pickled peppers.' )
>>>> >>>fh.close()
>>>> >>>fr = open ( 'info.txt', 'r')
>>>> >>>fr.readline()
>>>> 'peter piper picked a pack of pickled peppers.'
>>>> >>>fr.close()
>>>>
>>>> or whatever.
>>>> But do you have a need to use pickling?
>>>> --
>>>> Alexander
>>>> 7D9C597B
>>>>
>>>>
>>>> --------------------------------------------------------------------------
>>>>
>>>> Hey Alexander,
>>>> I had to try it before I went to sleep.
>>>> No good. I got an error msg. TypeError: must be str, not list.
>>>> So I guess that may be why i had went with pickling. I needed something
>>>> that would work with a list. Unless there is some other way?
>>>> Thanks again for taking the time to help out.
>>>>
>>>> Ken
>>>>
>>>>
>>> Ken, pickling is used when one wants to send information through a
>>> network or communicate with a database. Somebody else here knows more
>>> about pickling than I do. As for your list problem... I'm not exactly
>>> certain what you're trying to do. But I'm going with the idea that you
>>> have two files of information, one contains strings you like, and the
>>> other contains strings you dislike. And you want to read and write
>>> this information using Python.
>>>
>>>>>> like = [ 'orange', 'blue', 'red' ] #things I like
>>>>>> dislike = [ 'apples', 'bronze', 'bananas' ] #things I dislike
>>>>>> fh = open ( 'likes.txt', 'w' ) #let's open a file stream to write
>>>
>>> # fh is my shorthand for "file handle"
>>> #writing a list to a file stream:
>>>
>>>>>> for index in range( len( like )):
>>> fh.write( like[ index ] )
>>> fh.write ( '\n' ) #here i add a new line, maybe somebody else
>>> #knows a better way to avoid this?
>>>
>>>>>> fh.close()
>>>
>>> #now let's read that information into a list
>>>>>> fr = open ( 'info.txt' ) #I'm using python 3.2
>>>>>> mylistoflikes = fr.readlines()
>>>>>> mylistoflikes
>>> [ 'orange\n' , 'blue\n' , 'red\n' ]
>>>>>> fr.close()
>>>
>>> --
>>> Alexander
>>> 7D9C597B
>>> _______________________________________________
>>> Tutor maillist ?- ?Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>> First, pickle is used to store data objects.? If you just want to
>> store text, you just write it and read it back from your file.? But
>> there are situations where you want to save an object.? Maybe you want
>> to have it available to another program.
>>
>> So, you nearly got through your example.? You pickled your lists, and
>> stored them, but you didn't retrieve them.
>>
>> Here is a link to review: http://wiki.python.org/moin/UsingPickle
>>
>> Here is my version of your program.? It worked for me.? copy and paste
>> it in a file, and try it
>> -----------------------------------------------
>> import pickle
>>
>>
>> ArtyKlikes = (1,2,3)
>> ArtyKDislikes = (4,5,6)
>>
>> file1 = open("ArtyKlikes.p", "ab")? # likesList
>> file2 = open("ArtyDislikes.p", "ab")? # dislikes
>>
>> pickle.dump(ArtyKlikes, file1)
>> pickle.dump(ArtyKDislikes, file2)
>>
>> file1.close()
>> file2.close()
>>
>> ArtyLikes = pickle.load(open("ArtyKlikes.p", 'rb'))
>> ArtyDisLikes = pickle.load(open("ArtyDislikes.p", 'rb'))
>>
>> print ArtyLikes
>> print ArtyDisLikes
>>
>> --
>> Joel Goldstick
>>
>>
> Ken,
>
> First of all, always remember to reply to all on the list.? That keeps
> everyone in the loop.
> Second, don't 'top post'.? Write your comments at the end of the
> thread so that people can follow the conversation.? Sometimes its
> useful to intersperse comments in someone's previous email.
>
> Writing text to a file and reading it is useful, and pretty easy to
> understand.? But when you say you want to write a list you have to
> start to understand what a list really is (or a dict or some other
> object).? A list is not only the values in the list, it is also the
> code that lets a list do what lists do.? Things like:
>
> ? for something in mylist:
> ? ? ? # do something with 'something'
> or:
> ? print mylist[2]
>
> and so on.
>
> So, pickle is doing a whole lot more than writing '(1,2,3)' to your
> file.? It knows it is a list and it stores all it needs to about the
> list, including your specific list items.
>
>
>
>
>
>
> --
> Joel Goldstick
>
>
Go to the link I listed above.  It has examples.  I think you can use
one file and keep writing pickles to it.  But I've not used pickling,
so if it was me I would play around with it and see what you find out.
 The link has a simple example and other links to more complex
situations.


-- 
Joel Goldstick

From krush1954 at yahoo.com  Wed Jan 25 18:35:35 2012
From: krush1954 at yahoo.com (ken brockman)
Date: Wed, 25 Jan 2012 09:35:35 -0800 (PST)
Subject: [Tutor] how to read and write to a file
In-Reply-To: <CAPM-O+w_qpQ615N2ci2F7-LjY3FDRVUQE5o+hy7HmFeAWQrnSg@mail.gmail.com>
References: <1327493955.63824.YahooMailNeo@web39306.mail.mud.yahoo.com>
	<CANS6qmCnKe7QD0havRYj8YoZvB3vxY5rPowQdL2fD9-Kr=nJ3w@mail.gmail.com>
	<1327498347.23324.YahooMailNeo@web39302.mail.mud.yahoo.com>
	<CANS6qmCcehiemj3Dc52J7vPsXaWhk7+vq2gseewKxhMoTA91Aw@mail.gmail.com>
	<CAPM-O+wEBPV_kXfrGoTfqtoiZW0FyZkzuGs8ZgdJWoca_goROg@mail.gmail.com>
	<1327506625.57224.YahooMailNeo@web39306.mail.mud.yahoo.com>
	<CAPM-O+wA_Yrix3jiOe2Cqzsbqh-SBK2wbf6wxPT-9=VdWcpn9w@mail.gmail.com>
	<1327509050.61745.YahooMailNeo@web39302.mail.mud.yahoo.com>
	<CAPM-O+w_qpQ615N2ci2F7-LjY3FDRVUQE5o+hy7HmFeAWQrnSg@mail.gmail.com>
Message-ID: <1327512935.14394.YahooMailNeo@web39301.mail.mud.yahoo.com>

Joel, thanks your  first suggest worked great, except that it only reads my first item instead of the whole list. I will have to do some more research on the topic, but i do appreciate your giving me a leg up.
Also I don't understand why my last response was once again at the top of the list? I entered the reply at the window in the bottom of the email, like I had before.?Is that not the way? jeez.. I gotta get some zzzz's, I'm almost afraid to hit the reply button , I don't want to screw up once again..
Ken


________________________________
 From: Joel Goldstick <joel.goldstick at gmail.com>
To: ken brockman <krush1954 at yahoo.com> 
Cc: tutor at python.org 
Sent: Wednesday, January 25, 2012 12:00 PM
Subject: Re: [Tutor] how to read and write to a file
 
On Wed, Jan 25, 2012 at 11:30 AM, ken brockman <krush1954 at yahoo.com> wrote:
> Okay, got ya. Mea Culpa.
> Being misanthropic by nature I've not used or engaged??in a interactive
> forum such as this one before .
> I do grasp that a list is more then just the information it contains. So,
> does that mean i go with pickling? And can I save??two lists in one pickled
> file, or no?
>
> Thanks one and all, for the help.
> Ken
> ________________________________
> From: Joel Goldstick <joel.goldstick at gmail.com>
> To: ken brockman <krush1954 at yahoo.com>
> Cc: tutor at python.org
> Sent: Wednesday, January 25, 2012 11:04 AM
>
> Subject: Re: [Tutor] how to read and write to a file
>
> On Wed, Jan 25, 2012 at 10:50 AM, ken brockman <krush1954 at yahoo.com> wrote:
>> Thank you Joel and Alexander for your time and input.
>> I had just wanted to be able to store a list and read and write to it. But
>> it seems reading and writing is no go with lists, only strings, or no? Is
>> there a simply way I can tweak the read write feature to do lists? I'm
>> sorry
>> if I seem a tad slow on the uptick, I'm just starting to get
>> into?programming?and being up all night is not helping my comprehension
>> skills none. ?I've not as yet tried either of your suggestions, but from
>> what I can gather pickling is not the right tool for the job at hand. I'm
>> not looking to have it read by another program nor send it over a network.
>>
>> Also I have two lists and two files. Is it possible to store both lists in
>> one file? I wouldn't?imagine you could, but?hey,?doesn't hurt to ask.
>> Thanks again.
>>
>> Ken
>>
>> ________________________________
>> From: Joel Goldstick <joel.goldstick at gmail.com>
>> To: Alexander <rhettnaxel at gmail.com>
>> Cc: ken brockman <krush1954 at yahoo.com>; tutor at python.org
>> Sent: Wednesday, January 25, 2012 9:54 AM
>>
>> Subject: Re: [Tutor] how to read and write to a file
>>
>> On Wed, Jan 25, 2012 at 9:14 AM, Alexander <rhettnaxel at gmail.com> wrote:
>>> On Wed, Jan 25, 2012 at 8:32 AM, ken brockman <krush1954 at yahoo.com>
>>> wrote:
>>>>
>>>>
>>>> ________________________________
>>>> From: Alexander <rhettnaxel at gmail.com>
>>>> To: ken brockman <krush1954 at yahoo.com>
>>>> Cc: "tutor at python.org" <tutor at python.org>
>>>> Sent: Wednesday, January 25, 2012 7:38 AM
>>>> Subject: Re: [Tutor] how to read and write to a file
>>>>
>>>>
>>>>
>>>> On Wed, Jan 25, 2012 at 7:19 AM, ken brockman <krush1954 at yahoo.com>
>>>> wrote:
>>>>
>>>> I would like to write to and read from a file from python. I wanted to
>>>> use the file to save input to the program in a list. I have been looking
>>>> around and there seems to be several ways to go about it. I tried
>>>> pickling,
>>>> but am having an issue with it. What would be the correct way to
>>>> accomplish
>>>> this? I have tried?several?ways, but to no avail. I get no error msg.
>>>> but
>>>> the list isn't retaining the info.?Is pickling even the best way to do
>>>> it.
>>>>
>>>> file1 = open("ArtyKlikes.p", "ab") ?# likesList
>>>> file2 = open("ArtyDislikes.p", "ab") ?# dislikes
>>>>
>>>> pickle.dump(likesList, file1)
>>>> pickle.dump(dislikeList, file2)
>>>>
>>>> file1.close()
>>>> file2.close()
>>>>
>>>> Any help would be greatly appreciated.
>>>>
>>>> _______________________________________________
>>>> Tutor maillist ?- ?Tutor at python.org
>>>> To unsubscribe or change subscription options:
>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>
>>>>
>>>> Hi Ken. If you just want to read and write from a text file then you
>>>> don't need to pickle.
>>>> For example,
>>>> (the file info.txt exists)
>>>>
>>>> >>>fh = open ( 'info.txt', 'w' )
>>>> >>>fh.write ( 'peter piper picked a pack of pickled peppers.' )
>>>> >>>fh.close()
>>>> >>>fr = open ( 'info.txt', 'r')
>>>> >>>fr.readline()
>>>> 'peter piper picked a pack of pickled peppers.'
>>>> >>>fr.close()
>>>>
>>>> or whatever.
>>>> But do you have a need to use pickling?
>>>> --
>>>> Alexander
>>>> 7D9C597B
>>>>
>>>>
>>>> --------------------------------------------------------------------------
>>>>
>>>> Hey Alexander,
>>>> I had to try it before I went to sleep.
>>>> No good. I got an error msg. TypeError: must be str, not list.
>>>> So I guess that may be why i had went with pickling. I needed something
>>>> that would work with a list. Unless there is some other way?
>>>> Thanks again for taking the time to help out.
>>>>
>>>> Ken
>>>>
>>>>
>>> Ken, pickling is used when one wants to send information through a
>>> network or communicate with a database. Somebody else here knows more
>>> about pickling than I do. As for your list problem... I'm not exactly
>>> certain what you're trying to do. But I'm going with the idea that you
>>> have two files of information, one contains strings you like, and the
>>> other contains strings you dislike. And you want to read and write
>>> this information using Python.
>>>
>>>>>> like = [ 'orange', 'blue', 'red' ] #things I like
>>>>>> dislike = [ 'apples', 'bronze', 'bananas' ] #things I dislike
>>>>>> fh = open ( 'likes.txt', 'w' ) #let's open a file stream to write
>>>
>>> # fh is my shorthand for "file handle"
>>> #writing a list to a file stream:
>>>
>>>>>> for index in range( len( like )):
>>> fh.write( like[ index ] )
>>> fh.write ( '\n' ) #here i add a new line, maybe somebody else
>>> #knows a better way to avoid this?
>>>
>>>>>> fh.close()
>>>
>>> #now let's read that information into a list
>>>>>> fr = open ( 'info.txt' ) #I'm using python 3.2
>>>>>> mylistoflikes = fr.readlines()
>>>>>> mylistoflikes
>>> [ 'orange\n' , 'blue\n' , 'red\n' ]
>>>>>> fr.close()
>>>
>>> --
>>> Alexander
>>> 7D9C597B
>>> _______________________________________________
>>> Tutor maillist ?- ?Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>> First, pickle is used to store data objects.? If you just want to
>> store text, you just write it and read it back from your file.? But
>> there are situations where you want to save an object.? Maybe you want
>> to have it available to another program.
>>
>> So, you nearly got through your example.? You pickled your lists, and
>> stored them, but you didn't retrieve them.
>>
>> Here is a link to review: http://wiki.python.org/moin/UsingPickle
>>
>> Here is my version of your program.? It worked for me.? copy and paste
>> it in a file, and try it
>> -----------------------------------------------
>> import pickle
>>
>>
>> ArtyKlikes = (1,2,3)
>> ArtyKDislikes = (4,5,6)
>>
>> file1 = open("ArtyKlikes.p", "ab")? # likesList
>> file2 = open("ArtyDislikes.p", "ab")? # dislikes
>>
>> pickle.dump(ArtyKlikes, file1)
>> pickle.dump(ArtyKDislikes, file2)
>>
>> file1.close()
>> file2.close()
>>
>> ArtyLikes = pickle.load(open("ArtyKlikes.p", 'rb'))
>> ArtyDisLikes = pickle.load(open("ArtyDislikes.p", 'rb'))
>>
>> print ArtyLikes
>> print ArtyDisLikes
>>
>> --
>> Joel Goldstick
>>
>>
> Ken,
>
> First of all, always remember to reply to all on the list.? That keeps
> everyone in the loop.
> Second, don't 'top post'.? Write your comments at the end of the
> thread so that people can follow the conversation.? Sometimes its
> useful to intersperse comments in someone's previous email.
>
> Writing text to a file and reading it is useful, and pretty easy to
> understand.? But when you say you want to write a list you have to
> start to understand what a list really is (or a dict or some other
> object).? A list is not only the values in the list, it is also the
> code that lets a list do what lists do.? Things like:
>
> ? for something in mylist:
> ? ? ? # do something with 'something'
> or:
> ? print mylist[2]
>
> and so on.
>
> So, pickle is doing a whole lot more than writing '(1,2,3)' to your
> file.? It knows it is a list and it stores all it needs to about the
> list, including your specific list items.
>
>
>
>
>
>
> --
> Joel Goldstick
>
>
Go to the link I listed above.? It has examples.? I think you can use
one file and keep writing pickles to it.? But I've not used pickling,
so if it was me I would play around with it and see what you find out.
The link has a simple example and other links to more complex
situations.


-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120125/b6b2e755/attachment-0001.html>

From steve at pearwood.info  Thu Jan 26 00:15:25 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 26 Jan 2012 10:15:25 +1100
Subject: [Tutor] how to read and write to a file
In-Reply-To: <CAPM-O+wA_Yrix3jiOe2Cqzsbqh-SBK2wbf6wxPT-9=VdWcpn9w@mail.gmail.com>
References: <1327493955.63824.YahooMailNeo@web39306.mail.mud.yahoo.com>	<CANS6qmCnKe7QD0havRYj8YoZvB3vxY5rPowQdL2fD9-Kr=nJ3w@mail.gmail.com>	<1327498347.23324.YahooMailNeo@web39302.mail.mud.yahoo.com>	<CANS6qmCcehiemj3Dc52J7vPsXaWhk7+vq2gseewKxhMoTA91Aw@mail.gmail.com>	<CAPM-O+wEBPV_kXfrGoTfqtoiZW0FyZkzuGs8ZgdJWoca_goROg@mail.gmail.com>	<1327506625.57224.YahooMailNeo@web39306.mail.mud.yahoo.com>
	<CAPM-O+wA_Yrix3jiOe2Cqzsbqh-SBK2wbf6wxPT-9=VdWcpn9w@mail.gmail.com>
Message-ID: <4F208D0D.8030308@pearwood.info>

Joel Goldstick wrote:

> First of all, always remember to reply to all on the list.  That keeps
> everyone in the loop.
> Second, don't 'top post'.  Write your comments at the end of the
> thread so that people can follow the conversation.  Sometimes its
> useful to intersperse comments in someone's previous email.

"Sometimes"? I would say "almost always".

Please trim your replies. There is absolutely no need to repeat the ENTIRE 
comment thread, over and over and over again. Just quote what you need to 
establish context, and when directly answering a question or comment.

Otherwise, good advice: keep replies to the list unless you are making a 
personal/private comment, and email should be more like

   > Question
   Answer
   > Question
   Answer

instead of:


   Answer
   Answer
   > Question
   > Question


(And yes, I deliberately had one fewer answer than question in the second 
case. Top posting makes it MUCH easier to miss questions.)



-- 
Steven


From steve at pearwood.info  Thu Jan 26 00:30:25 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 26 Jan 2012 10:30:25 +1100
Subject: [Tutor] how to read and write to a file
In-Reply-To: <4F208D0D.8030308@pearwood.info>
References: <1327493955.63824.YahooMailNeo@web39306.mail.mud.yahoo.com>	<CANS6qmCnKe7QD0havRYj8YoZvB3vxY5rPowQdL2fD9-Kr=nJ3w@mail.gmail.com>	<1327498347.23324.YahooMailNeo@web39302.mail.mud.yahoo.com>	<CANS6qmCcehiemj3Dc52J7vPsXaWhk7+vq2gseewKxhMoTA91Aw@mail.gmail.com>	<CAPM-O+wEBPV_kXfrGoTfqtoiZW0FyZkzuGs8ZgdJWoca_goROg@mail.gmail.com>	<1327506625.57224.YahooMailNeo@web39306.mail.mud.yahoo.com>	<CAPM-O+wA_Yrix3jiOe2Cqzsbqh-SBK2wbf6wxPT-9=VdWcpn9w@mail.gmail.com>
	<4F208D0D.8030308@pearwood.info>
Message-ID: <4F209091.1020509@pearwood.info>

Steven D'Aprano wrote:

> (And yes, I deliberately had one fewer answer than question in the 
> second case. Top posting makes it MUCH easier to miss questions.)

Gah! Brain fart! Please ignore the comment in parentheses.




-- 
Steven

From marc.tompkins at gmail.com  Thu Jan 26 00:36:51 2012
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 25 Jan 2012 15:36:51 -0800
Subject: [Tutor] how to read and write to a file
In-Reply-To: <4F209091.1020509@pearwood.info>
References: <1327493955.63824.YahooMailNeo@web39306.mail.mud.yahoo.com>
	<CANS6qmCnKe7QD0havRYj8YoZvB3vxY5rPowQdL2fD9-Kr=nJ3w@mail.gmail.com>
	<1327498347.23324.YahooMailNeo@web39302.mail.mud.yahoo.com>
	<CANS6qmCcehiemj3Dc52J7vPsXaWhk7+vq2gseewKxhMoTA91Aw@mail.gmail.com>
	<CAPM-O+wEBPV_kXfrGoTfqtoiZW0FyZkzuGs8ZgdJWoca_goROg@mail.gmail.com>
	<1327506625.57224.YahooMailNeo@web39306.mail.mud.yahoo.com>
	<CAPM-O+wA_Yrix3jiOe2Cqzsbqh-SBK2wbf6wxPT-9=VdWcpn9w@mail.gmail.com>
	<4F208D0D.8030308@pearwood.info> <4F209091.1020509@pearwood.info>
Message-ID: <CAKK8jXa3ZykPn1AGeEroOixJMYGu1feQ_Rrp5=fpGkDce9OwSQ@mail.gmail.com>

On Wed, Jan 25, 2012 at 3:30 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> Steven D'Aprano wrote:
>
>  (And yes, I deliberately had one fewer answer than question in the second
>> case. Top posting makes it MUCH easier to miss questions.)
>>
>
> Gah! Brain fart! Please ignore the comment in parentheses.
>

And I thought you were just checking our FNORD reading comprehension.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120125/98db43a5/attachment.html>

From mjolewis at gmail.com  Thu Jan 26 04:36:51 2012
From: mjolewis at gmail.com (Michael Lewis)
Date: Wed, 25 Jan 2012 19:36:51 -0800
Subject: [Tutor] Error Checking/Defensive Programming
Message-ID: <CAE5MWfWh-9XwdWK+cz9tiTx-ZkSXhFGeCuQh=EoagkmugQ_4og@mail.gmail.com>

Hi everyone,

I am new to python and have a noob question.

Is it generally better to use try/except/else statements or if/elif/else?
Or, is there a time and place for each?

For a simple example, assume I want a user to enter a number

1) try:
       number = float(input('enter a number: ')
   except ValueError:
       print('enter a number.')
   else:
       print('you entered a number')

*OR*
*
*
2) number = float(input('enter a number: ')
    if number >=0 or < 0:
        print('you entered a number')
    else:
         print('enter a number.')

Thanks for the help.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120125/27179990/attachment.html>

From jeanpierreda at gmail.com  Thu Jan 26 04:49:10 2012
From: jeanpierreda at gmail.com (Devin Jeanpierre)
Date: Wed, 25 Jan 2012 22:49:10 -0500
Subject: [Tutor] Error Checking/Defensive Programming
In-Reply-To: <CAE5MWfWh-9XwdWK+cz9tiTx-ZkSXhFGeCuQh=EoagkmugQ_4og@mail.gmail.com>
References: <CAE5MWfWh-9XwdWK+cz9tiTx-ZkSXhFGeCuQh=EoagkmugQ_4og@mail.gmail.com>
Message-ID: <CABicbJKyUmFqiiVLYFgwJeyu_12J9Su7yPirKtwFfOjdKBxM=A@mail.gmail.com>

On Wed, Jan 25, 2012 at 10:36 PM, Michael Lewis <mjolewis at gmail.com> wrote:
> Is it generally better to use try/except/else statements or if/elif/else?
> Or, is there a time and place for each?

There's a time and place for each. Most errors are indicated in the
form of an exception being raised, though.

> For a simple example, assume I want a user to enter a number
>
> 1) try:
> ? ? ? ?number = float(input('enter a number: ')
> ? ?except ValueError:
> ? ? ? ?print('enter a number.')
> ? ?else:
> ? ? ? ?print('you entered a number')
>
> OR
>
> 2) number =?float(input('enter a number: ')
> ? ? if number >=0 or < 0:
> ? ? ? ? print('you entered a number')
> ? ? else:
> ? ? ? ? ?print('enter a number.')
>

float(x) doesn't return anything if the value it's passed can't be
converted to a float. The first way is the only way.

-- Devin

From steve at alchemy.com  Thu Jan 26 04:54:22 2012
From: steve at alchemy.com (Steve Willoughby)
Date: Wed, 25 Jan 2012 19:54:22 -0800
Subject: [Tutor] Error Checking/Defensive Programming
In-Reply-To: <CABicbJKyUmFqiiVLYFgwJeyu_12J9Su7yPirKtwFfOjdKBxM=A@mail.gmail.com>
References: <CAE5MWfWh-9XwdWK+cz9tiTx-ZkSXhFGeCuQh=EoagkmugQ_4og@mail.gmail.com>
	<CABicbJKyUmFqiiVLYFgwJeyu_12J9Su7yPirKtwFfOjdKBxM=A@mail.gmail.com>
Message-ID: <4F20CE6E.9060903@alchemy.com>

On 25-Jan-12 19:49, Devin Jeanpierre wrote:
> On Wed, Jan 25, 2012 at 10:36 PM, Michael Lewis<mjolewis at gmail.com>  wrote:
>>      if number>=0 or<  0:

As long as we're helping with this, I'll just add a comment about this 
conditional statement.  First, if you string together two expressions 
with "or" between them, they must each be complete statements.
number>=0 makes sense, but what does <0 mean?  You'd really write it as

if number >= 0 or number < 0:

However, that doesn't make sense because if "number" is something that 
can be compared with integers like 0, it will either be >= 0 or < 0, so 
the condition will always be true.  If "number" contains something that 
doesn't make sense to compare like that, then it just won't work (i.e., 
it'll likely throw an exception).  (usually :)


-- 
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C

From modulok at gmail.com  Thu Jan 26 05:24:32 2012
From: modulok at gmail.com (Modulok)
Date: Wed, 25 Jan 2012 21:24:32 -0700
Subject: [Tutor] Error Checking/Defensive Programming
In-Reply-To: <CAE5MWfWh-9XwdWK+cz9tiTx-ZkSXhFGeCuQh=EoagkmugQ_4og@mail.gmail.com>
References: <CAE5MWfWh-9XwdWK+cz9tiTx-ZkSXhFGeCuQh=EoagkmugQ_4og@mail.gmail.com>
Message-ID: <CAN2+EpbCcsm0iZ1SStMpwsCvHSL3jif3m69mNU8VwSZ0Ppn56A@mail.gmail.com>

It's easier to ask for forgiveness than permission. Ask yourself "Is this an
action that could fail in a specific way?" If yes, you need try/except. If no,
you probably need if/else. When dealing with data such as user input or opening
files and so forth, use try/except. When those actions fail, they fail in
highly specific ways. (No read/write access, no space, invalid user data, etc.)

    while True:
        try:
            number = float(raw_input("Enter a number between 1-10: "))
        except ValueError:
            print("Error: You need to enter a number.")
        else:
            # If they got this far, we have a number of some kind.
            # Check that it is in the valid range:
            if number <= 10 and number >= 1:
                # It's valid, stop the loop!
                break;
            else:
                print("Error: Number must be in the range of 1-10.")
    print("Yay, the number %.2f!" % number)


On the other hand, if I was looking for an internal condition, I would use
if/else:

    win_number = 3
    if number == 3:
        print("You won!")
    else:
        print("You loose!")


The rule doesn't always hold true, but it's a general guideline.

Hope that helps.
-Modulok-

On 1/25/12, Michael Lewis <mjolewis at gmail.com> wrote:
> Hi everyone,
>
> I am new to python and have a noob question.
>
> Is it generally better to use try/except/else statements or if/elif/else?
> Or, is there a time and place for each?
>
> For a simple example, assume I want a user to enter a number
>
> 1) try:
>        number = float(input('enter a number: ')
>    except ValueError:
>        print('enter a number.')
>    else:
>        print('you entered a number')
>
> *OR*
> *
> *
> 2) number = float(input('enter a number: ')
>     if number >=0 or < 0:
>         print('you entered a number')
>     else:
>          print('enter a number.')
>
> Thanks for the help.
>

From __peter__ at web.de  Thu Jan 26 09:03:11 2012
From: __peter__ at web.de (Peter Otten)
Date: Thu, 26 Jan 2012 09:03:11 +0100
Subject: [Tutor] Error Checking/Defensive Programming
References: <CAE5MWfWh-9XwdWK+cz9tiTx-ZkSXhFGeCuQh=EoagkmugQ_4og@mail.gmail.com>
	<CAN2+EpbCcsm0iZ1SStMpwsCvHSL3jif3m69mNU8VwSZ0Ppn56A@mail.gmail.com>
Message-ID: <jfr1br$v4i$1@dough.gmane.org>

Modulok wrote:

> if number <= 10 and number >= 1:

I like that you can spell that

if 1 <= number <= 10:

in Python. 



From stm.at.oc at googlemail.com  Thu Jan 26 12:03:49 2012
From: stm.at.oc at googlemail.com (stm atoc)
Date: Thu, 26 Jan 2012 12:03:49 +0100
Subject: [Tutor] TypeError: only length-1 arrays can be converted to Python
	scalars
Message-ID: <CAHNhTs435CuGP2LXFoegbnHbdG56V4Ug4+KiBp3-D2bQwrH_4g@mail.gmail.com>

Hi,

I have a question regarding the TypeError.

I have this script as follows in Python. I have run a program in Fortran:

# coding: utf-8
from pylab import *
import numpy
import matplotlib.pyplot as pyplot
import matplotlib.mlab as mlab

t=3600
N = 100
dz = 1.0

with open("act_out.list", "r") as f:
   z = numpy.array([float(v) for v in f.readline().split()[1:]])
zm = z*1.0e6

a = numpy.loadtxt("act_out.list", skiprows=3)
t=a[:,0]
nu = a[0:,1:N+1]
Conc = a[:, N+1:]
hsml=zeros((103))
cprof=zeros((103))

hsml[0]=-1300.
hsml[-2]=-300.
hsml[-1]=0.
hsml[1:-2]=z*1000000-300.

cprof[0]=50.
cprof[-2]=500.
cprof[-1]=500.

idx=int(where(t==1800)[0])
cprof[1:-2]=Conc[idx]

lw = 2.0
dpi = 80
figure(figsize=(8,8),dpi=dpi)
pyplot.plot(cprof,hsml,'r-')

pyplot.xlabel('$Conc, mmol C m^3$')
pyplot.ylabel('$Hsml, micrometer$')
pyplot.grid(True)

legend()
savefig('Conc.png')
show()

after runing Python, I hav ethis massage:

 TypeError: only length-1 arrays can be converted to Python scalars

Any suggestion?  in fact, what I missed and what I should add to have
a right result!

Thanks in advance,
Sue

From __peter__ at web.de  Thu Jan 26 13:01:47 2012
From: __peter__ at web.de (Peter Otten)
Date: Thu, 26 Jan 2012 13:01:47 +0100
Subject: [Tutor] TypeError: only length-1 arrays can be converted to
	Python scalars
References: <CAHNhTs435CuGP2LXFoegbnHbdG56V4Ug4+KiBp3-D2bQwrH_4g@mail.gmail.com>
Message-ID: <jfrfb6$uor$1@dough.gmane.org>

stm atoc wrote:

> Hi,
> 
> I have a question regarding the TypeError.
> 
> I have this script as follows in Python. I have run a program in Fortran:
> 
> # coding: utf-8
> from pylab import *
> import numpy
> import matplotlib.pyplot as pyplot
> import matplotlib.mlab as mlab
> 
> t=3600
> N = 100
> dz = 1.0
> 
> with open("act_out.list", "r") as f:
>    z = numpy.array([float(v) for v in f.readline().split()[1:]])
> zm = z*1.0e6
> 
> a = numpy.loadtxt("act_out.list", skiprows=3)
> t=a[:,0]
> nu = a[0:,1:N+1]
> Conc = a[:, N+1:]
> hsml=zeros((103))
> cprof=zeros((103))
> 
> hsml[0]=-1300.
> hsml[-2]=-300.
> hsml[-1]=0.
> hsml[1:-2]=z*1000000-300.
> 
> cprof[0]=50.
> cprof[-2]=500.
> cprof[-1]=500.
> 
> idx=int(where(t==1800)[0])
> cprof[1:-2]=Conc[idx]
> 
> lw = 2.0
> dpi = 80
> figure(figsize=(8,8),dpi=dpi)
> pyplot.plot(cprof,hsml,'r-')
> 
> pyplot.xlabel('$Conc, mmol C m^3$')
> pyplot.ylabel('$Hsml, micrometer$')
> pyplot.grid(True)
> 
> legend()
> savefig('Conc.png')
> show()
> 
> after runing Python, I hav ethis massage:
> 
>  TypeError: only length-1 arrays can be converted to Python scalars
> 
> Any suggestion?  in fact, what I missed and what I should add to have
> a right result!

By retyping the error message or omitting the traceback you are stripping 
off information that is valuable for debugging your problem. Always cut and 
paste the complete traceback.
Also, I cannot run your script as it relies upon data that you don't 
provide. Again, debugging becomes easier if you make your script self-
contained, e. g. set 'a' to some value explicitly with

a = numpy.array([...])

Anyway, here's my guess:

The t array has more than one 1800 entry:

>>> t = numpy.array([1., 1800., 1800.])
>>> numpy.where(t==1)
(array([0]),)
>>> int(numpy.where(t==1)[0])
0
>>> int(numpy.where(t==1800)[0])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: only length-1 arrays can be converted to Python scalars

I don't know what you are trying to do; if you are content with the index of 
the first occurrence of 1800 and are sure there is always at least one you 
could write

idx = numpy.where(t==1800)[0][0]



From rocklearnpython at gmail.com  Thu Jan 26 16:22:05 2012
From: rocklearnpython at gmail.com (Navneet)
Date: Thu, 26 Jan 2012 16:22:05 +0100
Subject: [Tutor] Socket Programming
Message-ID: <4F216F9D.3060002@gmail.com>

Hi,

I am trying to create a chat program.(Programs are attached)
Please find the code below, where I am having the problem.

def run( self ):
     while 1:
             print "Hello There !!!!"
         print self.descriptors
         # Await an event on a readable socket descriptor
             (sread, swrite, sexc) = select.select( self.descriptors, 
[], [] )
         print sexc
             # Iterate through the tagged read descriptors
         print sread
             print "Hello There 1 !!!!"
         for sock in sread:


For this I am getting the output as below:
bash-3.1$ python Server.py
Enter the Port:...9009
ChatServer started on port 9009
Hello There !!!!
[<socket._socketobject object at 0x0000000002487660>]


But it is not printing the value of sread or "Hello There 1 !!!!!"





-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120126/dc130fa7/attachment.html>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: Server.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20120126/dc130fa7/attachment.ksh>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: testclientchat.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20120126/dc130fa7/attachment-0001.ksh>

From arunkumar413 at gmail.com  Thu Jan 26 22:27:36 2012
From: arunkumar413 at gmail.com (Arun Kumar)
Date: Fri, 27 Jan 2012 02:57:36 +0530
Subject: [Tutor] splitting the large file into small pieces and download
Message-ID: <CAN+mmKY=Jx1fZy6G+ggbte0B7EkDCtDuYaBVub-003X+WZ8kZw@mail.gmail.com>

Hi all,

I want to build a small download accelerator program. I want to know how to
split the file to be downloaded into small pieces and assign the each small
piece to a thread for downloading.
-- 
Thanks & Regards,

Arun Kumar
http://clicknscroll.blogspot.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120127/a82cad09/attachment.html>

From spawgi at gmail.com  Thu Jan 26 23:34:47 2012
From: spawgi at gmail.com (spawgi at gmail.com)
Date: Fri, 27 Jan 2012 04:04:47 +0530
Subject: [Tutor] Pythonic way of concatenation of elements in an array
Message-ID: <CACPRw_yiZMvmjXp6wyLnyJHM6c+51j2gP+=4sMXRPMGfqs7cqA@mail.gmail.com>

Hello,

My code is -

l = len(m)
item = str(m[1])
for i in range(2,l):
    item = item + "-" + str(m[i])

This code is part of a bigger function. It works fine. But I am not happy
with the way I have written it. I think there is a better (Pythonic) way to
rewrite it.
If anyone knows how to improve this snippet, I would be very thankful.

Thanks and Regards,
Sumod


-- 
http://spawgi.wordpress.com
We can do it and do it better.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120127/1eebf97c/attachment.html>

From steve at pearwood.info  Fri Jan 27 00:04:18 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 27 Jan 2012 10:04:18 +1100
Subject: [Tutor] Pythonic way of concatenation of elements in an array
In-Reply-To: <CACPRw_yiZMvmjXp6wyLnyJHM6c+51j2gP+=4sMXRPMGfqs7cqA@mail.gmail.com>
References: <CACPRw_yiZMvmjXp6wyLnyJHM6c+51j2gP+=4sMXRPMGfqs7cqA@mail.gmail.com>
Message-ID: <4F21DBF2.8090802@pearwood.info>

spawgi at gmail.com wrote:
> Hello,
> 
> My code is -
> 
> l = len(m)
> item = str(m[1])
> for i in range(2,l):
>     item = item + "-" + str(m[i])
> 
> This code is part of a bigger function. It works fine. But I am not happy
> with the way I have written it. I think there is a better (Pythonic) way to
> rewrite it.
> If anyone knows how to improve this snippet, I would be very thankful.

(1) Never use "l" as a variable name, as it looks too much like 1.


(2) Use meaningful names. When posting snippets for help, you should show 
example data.


(3) You almost never need to iterate over an index by hand. Instead iterate 
over the items themselves. That is, instead of this:

for i in len(sequence):
     do_something_with( sequence[i] )

do this instead:

for item in sequence:
     do_something_with( item )


and similar variations.


(4) When you want only part of a sequence, use slicing to extract just the 
parts you care about.


(5) When assembling strings from substrings, never use repeated concatenation 
using + as that can be EXTREMELY slow. Use str.join to build the string in one 
assignment, instead of multiple assignments.

Your code shown above is *very* inefficient and will be PAINFULLY slow if m is 
very large. To understand why, you should read this article:

http://www.joelonsoftware.com/articles/fog0000000319.html

In this case, you can replace your snippet with this:

result = '-'.join(str(item) for item in m[1:])



For example:

py> m = [1, 2, "hello world", (23, 42), 5]
py> '-'.join(str(item) for item in m[1:])
'2-hello world-(23, 42)-5'



-- 
Steven


From wprins at gmail.com  Fri Jan 27 00:12:01 2012
From: wprins at gmail.com (Walter Prins)
Date: Thu, 26 Jan 2012 23:12:01 +0000
Subject: [Tutor] splitting the large file into small pieces and download
In-Reply-To: <CAN+mmKY=Jx1fZy6G+ggbte0B7EkDCtDuYaBVub-003X+WZ8kZw@mail.gmail.com>
References: <CAN+mmKY=Jx1fZy6G+ggbte0B7EkDCtDuYaBVub-003X+WZ8kZw@mail.gmail.com>
Message-ID: <CANLXbfBwLsyX8=LxRj5ZOiC4yW74bvywBQORodDiV8GfD7NFuQ@mail.gmail.com>

Hi Arun,

On 26 January 2012 21:27, Arun Kumar <arunkumar413 at gmail.com> wrote:
> I want to build a small download accelerator program. I want to know how to
> split the file to be downloaded into small pieces and assign the each small
> piece to a thread for downloading.

OK, so what else have you tried and what are you having problems with?
 Or have you just come up with that requirement spec and nothing else?
 While we're not going to write your program for you, we'd be willing
to help you with specific problems you may be stuck on.  I'd like to
add: This is not strictly speaking a Python language/tutoring
question, and really more of a general internet programming question,
so you may be better off asking elsewhere, such as (perhaps)
http://stackoverflow.com/

Some other questions: Do you understand websites and http traffic and
how to do this with Python well enough to download files directly
(without splitting them up) already? Do you understand threads and how
to use them already?   Obviously these 2 things are neccesary (though
not sufficient) conditions for you to be able to have a chance at
writing your program.

HTH,

Walter

From 0101amt at gmail.com  Fri Jan 27 00:20:32 2012
From: 0101amt at gmail.com (amt)
Date: Fri, 27 Jan 2012 01:20:32 +0200
Subject: [Tutor] Why do you have to close files?
Message-ID: <CAEQEn03WKcpr+gfUx8O0L7p0TcWAcK2hTHGNTfCaqpWDQsfkJA@mail.gmail.com>

Exercise 17, extra credit 6 Learn python the hard way: Find out why
you had to do output.close() in the code.


Code:
from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)


input = open(from_file)
indata = input.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()

output = open(to_file, 'w')
output.write(indata)

print "Alright, all done."

output.close()
input.close()


I don't get it. If you don't close input and output it works exactly
the same as if you would close them, so why do you have to do
output.close() and input.close()?

Also does it matter if you do: input.close() and then output.close()?
Is there an order to follow?



Thanks in advance, amt.

From ian.douglas at iandouglas.com  Fri Jan 27 00:27:00 2012
From: ian.douglas at iandouglas.com (ian douglas)
Date: Thu, 26 Jan 2012 15:27:00 -0800
Subject: [Tutor] Why do you have to close files?
In-Reply-To: <CAEQEn03WKcpr+gfUx8O0L7p0TcWAcK2hTHGNTfCaqpWDQsfkJA@mail.gmail.com>
References: <CAEQEn03WKcpr+gfUx8O0L7p0TcWAcK2hTHGNTfCaqpWDQsfkJA@mail.gmail.com>
Message-ID: <4F21E144.9020904@iandouglas.com>

On 1/26/12 3:20 PM, amt wrote:
> Exercise 17, extra credit 6 Learn python the hard way: Find out why
> you had to do output.close() in the code.
>
>
> Code:
>
> output.close()
> input.close()
>
>
> I don't get it. If you don't close input and output it works exactly
> the same as if you would close them, so why do you have to do
> output.close() and input.close()?
>
> Also does it matter if you do: input.close() and then output.close()?
> Is there an order to follow?
>
There's no order to follow, and it's really more about cleaning up after 
yourself than being a necessity. If you were writing to real files, your 
operating system would limit how many open files you could have at any 
time, so you want to make sure you close file handles you're no longer 
using.

From walksloud at gmail.com  Fri Jan 27 00:48:25 2012
From: walksloud at gmail.com (Andre' Walker-Loud)
Date: Thu, 26 Jan 2012 15:48:25 -0800
Subject: [Tutor] Why do you have to close files?
In-Reply-To: <4F21E144.9020904@iandouglas.com>
References: <CAEQEn03WKcpr+gfUx8O0L7p0TcWAcK2hTHGNTfCaqpWDQsfkJA@mail.gmail.com>
	<4F21E144.9020904@iandouglas.com>
Message-ID: <CA2A75DA-FBE6-4ED8-B648-6E64EECDD3D7@gmail.com>

>> Exercise 17, extra credit 6 Learn python the hard way: Find out why
>> you had to do output.close() in the code.
>> 
>> 
>> Code:
>> 
>> output.close()
>> input.close()
>> 
>> 
>> I don't get it. If you don't close input and output it works exactly
>> the same as if you would close them, so why do you have to do
>> output.close() and input.close()?
>> 
>> Also does it matter if you do: input.close() and then output.close()?
>> Is there an order to follow?
>> 
> There's no order to follow, and it's really more about cleaning up after yourself than being a necessity. If you were writing to real files, your operating system would limit how many open files you could have at any time, so you want to make sure you close file handles you're no longer using.

Also - from experience, output.close() can be very important.

eg. - I often use python to
1- create an initialization file
2 - use this initialization file with some executable code

These are steps I perform in the same script.  One time, I forgot to do "output.close()" before handing my file to the executable.  Then for two weeks, I was wondering what was wrong with my code?!?  It compiled damn it, and if I ran my job (this is on a big computing cluster) in interactive mode, everything worked!?!  What was going wrong?????  ahhhh

Well, when I finally realized I forgot to "close()" my file, I felt rather silly.

The problem is python does not actually write the file to disk until you execute "output.close()".  When you end your session, if you forgot to do "output.close()" it will write it to disk for you (it has all the time for me at least).  But in my case, it was the same python "session" in which I was trying to both write the file, and then use it.


Andre


From d at davea.name  Fri Jan 27 00:48:13 2012
From: d at davea.name (Dave Angel)
Date: Thu, 26 Jan 2012 18:48:13 -0500
Subject: [Tutor] Why do you have to close files?
In-Reply-To: <CAEQEn03WKcpr+gfUx8O0L7p0TcWAcK2hTHGNTfCaqpWDQsfkJA@mail.gmail.com>
References: <CAEQEn03WKcpr+gfUx8O0L7p0TcWAcK2hTHGNTfCaqpWDQsfkJA@mail.gmail.com>
Message-ID: <4F21E63D.5030103@davea.name>

On 01/26/2012 06:20 PM, amt wrote:
> Exercise 17, extra credit 6 Learn python the hard way: Find out why
> you had to do output.close() in the code.
>
>
> Code:
> from sys import argv
> from os.path import exists
>
> script, from_file, to_file = argv
>
> print "Copying from %s to %s" % (from_file, to_file)
>
>
> input = open(from_file)
> indata = input.read()
>
> print "The input file is %d bytes long" % len(indata)
>
> print "Does the output file exist? %r" % exists(to_file)
> print "Ready, hit RETURN to continue, CTRL-C to abort."
> raw_input()
>
> output = open(to_file, 'w')
> output.write(indata)
>
> print "Alright, all done."
>
> output.close()
> input.close()
>
>
> I don't get it. If you don't close input and output it works exactly
> the same as if you would close them, so why do you have to do
> output.close() and input.close()?
>
> Also does it matter if you do: input.close() and then output.close()?
> Is there an order to follow?
>
>
This is an extra credit question, after all.  So it must be a little 
subtle, and it is.

First, Python (the language) does not promise that it will close the 
files for you. The operating system does, when the program exits.  In 
this trivial program, that's right away.  But if your program does 
something else for a while, or repeats this sequence of steps dozens of 
times, you could run out of resources, or overwrite something.

CPython, the most common implementation, does promise that the file will 
be closed when the usage count of the file object goes away.  So if you 
did any of the following, it would close the file:

    1) del output
     2) output = None
    3) output = open(someother_file, "w")

However, that's an optimization within CPython, and not necessarily 
guaranteed for other Python implementations, like IronPython or Jython.

Second, some operating system platforms won't let the same file be 
simultaneously open for readonly and for write.  So if the two filenames 
happened to be the same file (through symlink or other mechanism, or 
even using two different ways to describe the same file), you might get 
an error trying to write without having closed the input file.

Try putting the same name for both input and output file, see what it 
does.  Or use an absolute path for the input filename and a relative 
path to the same place for the output file.

The place to close the input file is right after you're done reading the 
data, and before opening the output file.


-- 

DaveA


From steve at pearwood.info  Fri Jan 27 00:50:03 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 27 Jan 2012 10:50:03 +1100
Subject: [Tutor] Why do you have to close files?
In-Reply-To: <CAEQEn03WKcpr+gfUx8O0L7p0TcWAcK2hTHGNTfCaqpWDQsfkJA@mail.gmail.com>
References: <CAEQEn03WKcpr+gfUx8O0L7p0TcWAcK2hTHGNTfCaqpWDQsfkJA@mail.gmail.com>
Message-ID: <4F21E6AB.8090608@pearwood.info>

amt wrote:

> I don't get it. If you don't close input and output it works exactly
> the same as if you would close them, so why do you have to do
> output.close() and input.close()?

(1) It is a matter of good programming practice. If you don't close them 
yourself, Python will eventually close them for you. In some versions of 
Python, that might be the instant they are no longer being used; in others, it 
might not happen for a long time. Under some circumstances, it might not 
happen at all.

(2) When writing to a file, the data may not be written to disk until the file 
is closed. When you say "output.write(...)", the data is often cached in 
memory and doesn't hit the hard drive until the file is closed[1]. The longer 
you keep the file open, the greater the chance that you will lose data.

(3) Since your operating system has strict limits on how many file handles can 
be kept open at any one instant, it is best to get into the habit of closing 
them when they aren't needed and not wait for "maid service" to clean up after 
you.

(4) Also, some operating systems (Windows, in particular) treat open files as 
locked and private. While you have a file open, no other program can also open 
it, even just to read the data. This spoils backup programs, anti-virus 
scanners, etc.


> Also does it matter if you do: input.close() and then output.close()?
> Is there an order to follow?

It makes no real difference, but I prefer to close output files first, so they 
get written to disk a microsecond sooner than they otherwise would have.



[1] Annoyingly, modern hard drives often themselves have their own internal 
memory cache, so even when the operating system flushes data to the disk, 
there is no guarantee that the data will have actually been written to the 
disk platter. But there's nothing really you can do about that except hope 
that the power doesn't go out in the middle of writing to disk!


-- 
Steven


From sp6 at rice.edu  Fri Jan 27 01:19:39 2012
From: sp6 at rice.edu (sp6 at rice.edu)
Date: Thu, 26 Jan 2012 18:19:39 -0600
Subject: [Tutor] Question regarding setup.py
Message-ID: <20120126181939.14563npemci1j2qj@webmail.rice.edu>

Hi All,

I had a question regarding installing packages that I posted a couple  
of days ago. But I'm re-sending the question again.. this time with  
output so that it is clearer.

I am unable to install libraries using 'python setup.py install'

Say that I'm installing a package "kando". I extract it and I'm  
currently in its directory:

Output to dir:
dir
       11357    Aug 12 20:43:46 2011  COPYING.txt
        2769    Aug 12 20:46:34 2011  PKG-INFO
        1490    Aug 12 20:39:31 2011  README.txt
          56    Aug 05 20:06:46 2011  kando
        6362    Aug 12 20:35:23 2011  kando.py
         868    Oct 20 17:48:00 2011  setup.py

Next, I try and install kando and this is what I get:

python setup.py install
file kando.py (for module kando) not found
file kando.py (for module kando) not found
error: file '/var/sysmgr/vsh/kando' does not exist
Thu Oct 20 18:35:01 UTC 2011
running install
running build
running build_py
running build_scripts

I guess the installer is not looking in the right path for the files  
to be installed as it cannot find kando.py although I can see it in  
the output of dir. This is not specific to just kando. I have tried  
installing arithmetic-0.5 and other packages.
Can you please tell me how I can change the search path of the installer?
Thanks in advance.

Thanks,
San


From alan.gauld at btinternet.com  Fri Jan 27 02:16:56 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 27 Jan 2012 01:16:56 +0000
Subject: [Tutor] Why do you have to close files?
In-Reply-To: <CAEQEn03WKcpr+gfUx8O0L7p0TcWAcK2hTHGNTfCaqpWDQsfkJA@mail.gmail.com>
References: <CAEQEn03WKcpr+gfUx8O0L7p0TcWAcK2hTHGNTfCaqpWDQsfkJA@mail.gmail.com>
Message-ID: <jfstu8$m49$1@dough.gmane.org>

On 26/01/12 23:20, amt wrote:

> input = open(from_file)
> indata = input.read()
>  ...
>
> output = open(to_file, 'w')
> output.write(indata)
>
> print "Alright, all done."
>
> output.close()
> input.close()
>
>
> I don't get it. If you don't close input and output it works exactly
> the same as if you would close them, so why do you have to do
> output.close() and input.close()?

In this case it will work the same 99.9% of the time because when your 
program closes Python will kill all the file objects that you created 
and in the process the files will get written to the disk. However, to 
understand why you need to call close() in the general case you need to 
understand that when you do a write to a file the OS does not 
immediately write the data to the disk (it would be too slow). Instead 
it writes it to a holding area in memory (called a buffer) and then, 
every so often, it copies the buffer out to the real file. When you call 
close() one of the things that happens is that the buffer gets told to 
write to disk, even if it's not full yet. If you don't call close you 
can wind up with data missing from the end of your files.

The other thing that close does is releases the memory and other OS 
resources that are allocated to the file when you open it. Depending on 
the OS there may be limits to how many files can be open at once. Also 
the file may be locked until it is closed preventing other programs from 
accessing it. So in general, whenever you finish using a file, you 
should close it as a good habit... In fact it's a good idea to use a 
try/finally construct to guarantee that the file gets closed, especially 
if you are writing to it:

try:
    foo = open(myFiule,'w')
    # do stuff to foo
finally:
    foo.close()

The only exception to this is if you open the file like this:

with open(myfile) as aFile:
      # use aFile

This construct specifically guarantees to close the file for you at the 
end of the block.

It's one of those things that catches beginners out regularly because 
nine times out of ten not closing the file will seem to work fine then, 
once in a while, it fails and data gets corrupted.

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


From spawgi at gmail.com  Fri Jan 27 06:22:38 2012
From: spawgi at gmail.com (spawgi at gmail.com)
Date: Fri, 27 Jan 2012 10:52:38 +0530
Subject: [Tutor] Pythonic way of concatenation of elements in an array
In-Reply-To: <4F21DBF2.8090802@pearwood.info>
References: <CACPRw_yiZMvmjXp6wyLnyJHM6c+51j2gP+=4sMXRPMGfqs7cqA@mail.gmail.com>
	<4F21DBF2.8090802@pearwood.info>
Message-ID: <CACPRw_zDt2bjobZ6wxxdGTTV-XZ7TpGYhEMeE_irFhGVVuDGkQ@mail.gmail.com>

Hello Steven,

Thanks a lot for the detailed answer. I will implement your suggestions.
Really appreciate it.

Thanks and Regards,
Sumod

On Fri, Jan 27, 2012 at 4:34 AM, Steven D'Aprano <steve at pearwood.info>wrote:

> spawgi at gmail.com wrote:
>
>> Hello,
>>
>> My code is -
>>
>> l = len(m)
>> item = str(m[1])
>> for i in range(2,l):
>>    item = item + "-" + str(m[i])
>>
>> This code is part of a bigger function. It works fine. But I am not happy
>> with the way I have written it. I think there is a better (Pythonic) way
>> to
>> rewrite it.
>> If anyone knows how to improve this snippet, I would be very thankful.
>>
>
> (1) Never use "l" as a variable name, as it looks too much like 1.
>
>
> (2) Use meaningful names. When posting snippets for help, you should show
> example data.
>
>
> (3) You almost never need to iterate over an index by hand. Instead
> iterate over the items themselves. That is, instead of this:
>
> for i in len(sequence):
>    do_something_with( sequence[i] )
>
> do this instead:
>
> for item in sequence:
>    do_something_with( item )
>
>
> and similar variations.
>
>
> (4) When you want only part of a sequence, use slicing to extract just the
> parts you care about.
>
>
> (5) When assembling strings from substrings, never use repeated
> concatenation using + as that can be EXTREMELY slow. Use str.join to build
> the string in one assignment, instead of multiple assignments.
>
> Your code shown above is *very* inefficient and will be PAINFULLY slow if
> m is very large. To understand why, you should read this article:
>
> http://www.joelonsoftware.com/**articles/fog0000000319.html<http://www.joelonsoftware.com/articles/fog0000000319.html>
>
> In this case, you can replace your snippet with this:
>
> result = '-'.join(str(item) for item in m[1:])
>
>
>
> For example:
>
> py> m = [1, 2, "hello world", (23, 42), 5]
> py> '-'.join(str(item) for item in m[1:])
> '2-hello world-(23, 42)-5'
>
>
>
> --
> Steven
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>



-- 
http://spawgi.wordpress.com
We can do it and do it better.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120127/be211abf/attachment.html>

From walksloud at gmail.com  Fri Jan 27 07:44:17 2012
From: walksloud at gmail.com (Andre' Walker-Loud)
Date: Thu, 26 Jan 2012 22:44:17 -0800
Subject: [Tutor] Pythonic way of concatenation of elements in an array
In-Reply-To: <4F21DBF2.8090802@pearwood.info>
References: <CACPRw_yiZMvmjXp6wyLnyJHM6c+51j2gP+=4sMXRPMGfqs7cqA@mail.gmail.com>
	<4F21DBF2.8090802@pearwood.info>
Message-ID: <398952D4-9158-4496-9D28-B6D0FF07FC45@gmail.com>

Hi Steven,

> (5) When assembling strings from substrings, never use repeated concatenation using + as that can be EXTREMELY slow. Use str.join to build the string in one assignment, instead of multiple assignments.
> 
> Your code shown above is *very* inefficient and will be PAINFULLY slow if m is very large. To understand why, you should read this article:
> 
> http://www.joelonsoftware.com/articles/fog0000000319.html
> 
> In this case, you can replace your snippet with this:
> 
> result = '-'.join(str(item) for item in m[1:])

This was an interesting article.  I have only had one programming class, and that was 15 years ago or so, so these are not issues I am aware of.

I often find myself joining strings (and have mostly used + to do it).  An alternate method I use is, for eg.

>print('here is a string %s which has many variables %s %s %s I have to sort out' %(s1,s2,s3,s4))

where the various strings (s1 - s4) have been determined elsewhere, perhaps in a loop.

Is this method any better at combining strings than the +?  My first guess would be no, but that is really just a guess.


Thanks,

Andre

From stefan_ml at behnel.de  Fri Jan 27 08:54:16 2012
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 27 Jan 2012 08:54:16 +0100
Subject: [Tutor] Why do you have to close files?
In-Reply-To: <jfstu8$m49$1@dough.gmane.org>
References: <CAEQEn03WKcpr+gfUx8O0L7p0TcWAcK2hTHGNTfCaqpWDQsfkJA@mail.gmail.com>
	<jfstu8$m49$1@dough.gmane.org>
Message-ID: <jftl79$l3u$1@dough.gmane.org>

Alan Gauld, 27.01.2012 02:16:
> with open(myfile) as aFile:
>      # use aFile

I should add that this is the shortest, safest (as in "hard to get wrong")
and most readable way to open and close a file. It's worth getting used to.

Stefan


From breamoreboy at yahoo.co.uk  Fri Jan 27 09:39:16 2012
From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi)
Date: Fri, 27 Jan 2012 08:39:16 +0000
Subject: [Tutor] Pythonic way of concatenation of elements in an array
In-Reply-To: <398952D4-9158-4496-9D28-B6D0FF07FC45@gmail.com>
References: <CACPRw_yiZMvmjXp6wyLnyJHM6c+51j2gP+=4sMXRPMGfqs7cqA@mail.gmail.com>
	<4F21DBF2.8090802@pearwood.info>
	<398952D4-9158-4496-9D28-B6D0FF07FC45@gmail.com>
Message-ID: <jftnot$5c2$1@dough.gmane.org>

On 27/01/2012 06:44, Andre' Walker-Loud wrote:
> Hi Steven,
>
>> (5) When assembling strings from substrings, never use repeated concatenation using + as that can be EXTREMELY slow. Use str.join to build the string in one assignment, instead of multiple assignments.
>>
>> Your code shown above is *very* inefficient and will be PAINFULLY slow if m is very large. To understand why, you should read this article:
>>
>> http://www.joelonsoftware.com/articles/fog0000000319.html
>>
>> In this case, you can replace your snippet with this:
>>
>> result = '-'.join(str(item) for item in m[1:])
>
> This was an interesting article.  I have only had one programming class, and that was 15 years ago or so, so these are not issues I am aware of.
>
> I often find myself joining strings (and have mostly used + to do it).  An alternate method I use is, for eg.
>
>> print('here is a string %s which has many variables %s %s %s I have to sort out' %(s1,s2,s3,s4))
>
> where the various strings (s1 - s4) have been determined elsewhere, perhaps in a loop.
>
> Is this method any better at combining strings than the +?  My first guess would be no, but that is really just a guess.
>
>
> Thanks,
>
> Andre
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

You might like to take a look here 
http://wiki.python.org/moin/PythonSpeed/PerformanceTips#String_Concatenation
-- 
Cheers.

Mark Lawrence.


From alan.gauld at btinternet.com  Fri Jan 27 10:04:13 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 27 Jan 2012 09:04:13 +0000
Subject: [Tutor] Pythonic way of concatenation of elements in an array
In-Reply-To: <398952D4-9158-4496-9D28-B6D0FF07FC45@gmail.com>
References: <CACPRw_yiZMvmjXp6wyLnyJHM6c+51j2gP+=4sMXRPMGfqs7cqA@mail.gmail.com>
	<4F21DBF2.8090802@pearwood.info>
	<398952D4-9158-4496-9D28-B6D0FF07FC45@gmail.com>
Message-ID: <jftpam$fkv$1@dough.gmane.org>

On 27/01/12 06:44, Andre' Walker-Loud wrote:
> ...  I have only had one programming class, and that was 15 years ago or so,
 > ...so these are not issues I am aware of.
> I often find myself joining strings (and have mostly used + to do it).

String addition is OK in some languages, or at least better than in 
Python so it is not a universal rule of programming. In Python the big 
problem is that each addition operation creates a new string so Python 
spends a lot of time allocating bigger and bigger chunks of memory only 
to throw it away again.

>> print('here is a string %s which has many variables %s %s %s I have to sort out' %(s1,s2,s3,s4))
> ...
> Is this method any better at combining strings than the +?

It is quite a bit better because Python can pre-calculate how much 
memory is needed and do it once.

However, I wouldn't get too stressed on speed. String formatting has a 
lot of other advantages over join() and is fast enough most of the time.
I tend to use formatting more than join() in my own code, but join() is 
best if you are building up a string in a loop say. You can append the 
substrings to a list and then join the list at the end.

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


From evert.rol at gmail.com  Fri Jan 27 11:17:27 2012
From: evert.rol at gmail.com (Evert Rol)
Date: Fri, 27 Jan 2012 11:17:27 +0100
Subject: [Tutor] Question regarding setup.py
In-Reply-To: <20120126181939.14563npemci1j2qj@webmail.rice.edu>
References: <20120126181939.14563npemci1j2qj@webmail.rice.edu>
Message-ID: <45829416-4DC6-4458-B229-8BAF5921535F@gmail.com>

> I had a question regarding installing packages that I posted a couple of days ago. But I'm re-sending the question again.. this time with output so that it is clearer.
> 
> I am unable to install libraries using 'python setup.py install'
> 
> Say that I'm installing a package "kando". I extract it and I'm currently in its directory:
> 
> Output to dir:
> dir
>      11357    Aug 12 20:43:46 2011  COPYING.txt
>       2769    Aug 12 20:46:34 2011  PKG-INFO
>       1490    Aug 12 20:39:31 2011  README.txt
>         56    Aug 05 20:06:46 2011  kando
>       6362    Aug 12 20:35:23 2011  kando.py
>        868    Oct 20 17:48:00 2011  setup.py
> 
> Next, I try and install kando and this is what I get:
> 
> python setup.py install
> file kando.py (for module kando) not found
> file kando.py (for module kando) not found
> error: file '/var/sysmgr/vsh/kando' does not exist
> Thu Oct 20 18:35:01 UTC 2011
> running install
> running build
> running build_py
> running build_scripts

I assume you're running this in the unpacked directory (it's what you suggest, but I can't tell with 100% certainty.).
Then I can only think that the setup.py is misbehaving; the '/var/sysmgr/vsh/kando' mention suggests that. 
Usually, certainly for small libraries (this seems to be one), these are relatively small, so perhaps you can post it?
Also, check the README file for any installation suggestions.

Alternatively, if the contents of the kando/ directory just contains Python files, you could copy-paste that whole directory into your Python library installation directory. The latter is system dependent, but should be relatively easy to find out. 

Another thing I can think of that may cause problems, is that in the unpacked directory, there is both a kando directory (which presumably contains an __init__.py file) and a kando.py file.


> I guess the installer is not looking in the right path for the files to be installed as it cannot find kando.py although I can see it in the output of dir. This is not specific to just kando. I have tried installing arithmetic-0.5 and other packages.
> Can you please tell me how I can change the search path of the installer?

No, that's not how it works.
You just run python setup.py install in the directory, and Python will happily install the library correctly.
You can alter the *installation* path, using a flag like --prefix. Usually, I wouldn't recommend that.

  Evert

> Thanks in advance.
> 
> Thanks,
> San
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From suryak at live.com  Fri Jan 27 16:46:35 2012
From: suryak at live.com (Surya K)
Date: Fri, 27 Jan 2012 21:16:35 +0530
Subject: [Tutor] compile time calculator
Message-ID: <SNT130-W27F5CD1F9F21EB56ECD8D3A48E0@phx.gbl>


Hi,
I want to calculate compile time for my puzzles. Although I read about timeit(), I didn't really understand how it should be applied it.So, can anyone write a function for me please!!
I am looking for a function which should solve my puzzle and also show compile time. (Later, I should be able to delete that function before submitting my code)
The following way is what I am exactly looking at:
define a compile time function such that it should take all my puzzle code and provide compile time for it.
(I think timeit() should be called at each statement, which is not flexible, don't know exactly.)
can anyone write a program for me? please... 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120127/3a6b4c64/attachment.html>

From breamoreboy at yahoo.co.uk  Fri Jan 27 17:10:44 2012
From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi)
Date: Fri, 27 Jan 2012 16:10:44 +0000
Subject: [Tutor] compile time calculator
In-Reply-To: <SNT130-W27F5CD1F9F21EB56ECD8D3A48E0@phx.gbl>
References: <SNT130-W27F5CD1F9F21EB56ECD8D3A48E0@phx.gbl>
Message-ID: <jfui8f$b9a$1@dough.gmane.org>

On 27/01/2012 15:46, Surya K wrote:
> Hi,
>
> I want to calculate compile time for my puzzles. Although I read about
> timeit(), I didn't really understand how it should be applied it.
> So, can anyone write a function for me please!!
>
> I am looking for a function which should solve my puzzle and also show
> compile time. (Later, I should be able to delete that function before
> submitting my code)
>
> The following way is what I am exactly looking at:
>
> define a compile time function such that it should take all my puzzle
> code and provide compile time for it.
>
> (I think timeit() should be called at each statement, which is not
> flexible, don't know exactly.)
>
> can anyone write a program for me? please...
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Nobody will write code for you unless you show that you've made an 
attempt yourself.  Perhaps you're looking for the standard profile 
module?  Or trying optimization prematurely?  Or what?  Please give more 
information about the precise nature of your problem and you will get 
many very useful answers.

-- 
Cheers.

Mark Lawrence.


From alan.gauld at btinternet.com  Fri Jan 27 20:35:35 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 27 Jan 2012 19:35:35 +0000
Subject: [Tutor] compile time calculator
In-Reply-To: <SNT130-W27F5CD1F9F21EB56ECD8D3A48E0@phx.gbl>
References: <SNT130-W27F5CD1F9F21EB56ECD8D3A48E0@phx.gbl>
Message-ID: <jfuua8$8av$1@dough.gmane.org>

On 27/01/12 15:46, Surya K wrote:

> I want to calculate compile time for my puzzles.

I'm pretty sure from what follows you don't!
But just to be clear, compile time is the time Python spends converting 
your modules into .pyc files the first time they are imported after a 
change. Why you would want to time that I have no idea, and assume you 
don't really.

>  Although I read about timeit(),

timeit is used to measure *execution* times, it has nothing to do with 
compile times.

However, if you want to measure how long your code takes to run then it 
is relevant. Search the archive of this list for some good examples of 
using timeit. I seem to recall Steven wrote an excellent tutorial a few 
months ago.

> I am looking for a function which should solve my puzzle and also show
> compile time. (Later, I should be able to delete that function before
> submitting my code)

I'm afraid you'll need to solve the puzzle yourself. There is unlikely 
to be a ready made one lying around and folks on this list can help but 
we do not do your work for you. (And in this case couldn't since we 
don't know what your puzzle is! Or are you still talking about the Lucky 
numbers one from earlier?)

> define a compile time function such that it should take all my puzzle
> code and provide compile time for it.
>
> (I think timeit() should be called at each statement, which is not
> flexible, don't know exactly.)

Assuming you want run time not compile time you should probably look at 
the Python profiler - in the profile module. It's not totally intuitive 
to set up but the documents give examples. But it doesn't work at the 
line level but at functions.

But if you are still battling with the Lucky Number thing you really 
need to go back to the math, not the Python code. You need a new 
algorithm not tighter code. Wikipedia and Google might be more help than 
the profiler!

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


From rocklearnpython at gmail.com  Fri Jan 27 20:53:39 2012
From: rocklearnpython at gmail.com (Navneet)
Date: Fri, 27 Jan 2012 20:53:39 +0100
Subject: [Tutor] Socket Programming
In-Reply-To: <4F216F9D.3060002@gmail.com>
References: <4F216F9D.3060002@gmail.com>
Message-ID: <4F2300C3.4070703@gmail.com>

On 1/26/2012 4:22 PM, Navneet wrote:
> Hi,
>
> I am trying to create a chat program.(Programs are attached)
> Please find the code below, where I am having the problem.
>
> def run( self ):
>     while 1:
>             print "Hello There !!!!"
>         print self.descriptors
>         # Await an event on a readable socket descriptor
>             (sread, swrite, sexc) = select.select( self.descriptors, 
> [], [] )
>         print sexc
>             # Iterate through the tagged read descriptors
>         print sread
>             print "Hello There 1 !!!!"
>         for sock in sread:
>
>
> For this I am getting the output as below:
> bash-3.1$ python Server.py
> Enter the Port:...9009
> ChatServer started on port 9009
> Hello There !!!!
> [<socket._socketobject object at 0x0000000002487660>]
>
>
> But it is not printing the value of sread or "Hello There 1 !!!!!"
>
>
>
>
>
Hello All,

One more thing I want to add here is, I am trying to create the GUI 
based chat server.(Attached the programs.)
The concept is something like this:
I will start a server on a particular port and different Clients can 
interact with each other using that (more like a chat room )
Now I want to add the GUI part in a different module and want to call 
that module from client program.
But while executing the client1.py I am getting below error :



bash-3.1$ python Client1.py
Enter the server address:...9009
Traceback (most recent call last):
   File "Client1.py", line 53, in <module>
     c = ClientChat(serverport)
   File "Client1.py", line 24, in __init__
     gui.callGui()
   File "a:\FedEx\Exp\ClientGui.py", line 37, in callGui
     sendbutton =Button(f2, width = 5, height = 2, text = "Send", 
command = C.ClientChat.senddata())
TypeError: unbound method senddata() must be called with ClientChat 
instance as first argument (got nothing instead)












-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120127/df8a7055/attachment.html>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: Client1.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20120127/df8a7055/attachment.ksh>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: ClientGui.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20120127/df8a7055/attachment-0001.ksh>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: Server.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20120127/df8a7055/attachment-0002.ksh>

From steve at pearwood.info  Fri Jan 27 22:01:31 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 28 Jan 2012 08:01:31 +1100
Subject: [Tutor] compile time calculator
In-Reply-To: <SNT130-W27F5CD1F9F21EB56ECD8D3A48E0@phx.gbl>
References: <SNT130-W27F5CD1F9F21EB56ECD8D3A48E0@phx.gbl>
Message-ID: <4F2310AB.10100@pearwood.info>

Surya K wrote:

> can anyone write a program for me? please...


Certainly. My rate is AUD$80 per hour. Please write to me privately to discuss 
financial arrangements.



-- 
Steven

From steve at pearwood.info  Fri Jan 27 22:13:32 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 28 Jan 2012 08:13:32 +1100
Subject: [Tutor] Socket Programming
In-Reply-To: <4F2300C3.4070703@gmail.com>
References: <4F216F9D.3060002@gmail.com> <4F2300C3.4070703@gmail.com>
Message-ID: <4F23137C.7060005@pearwood.info>

Navneet wrote:

> One more thing I want to add here is, I am trying to create the GUI 
> based chat server.(Attached the programs.)


Please do not send large chunks of code like this, unless asked. Instead, you 
should try to produce a minimal example that demonstrates the problem. It 
should be:

* short (avoid code which has nothing to do with the problem)

* self-contained (other people must be able to run it)

* correct (it must actually fail in the way you say it fails)

See here for more: http://sscce.org/


In cutting your code down to a minimal example, 9 times out of 10 you will 
solve your problem yourself, and learn something in the process.


> bash-3.1$ python Client1.py
> Enter the server address:...9009
> Traceback (most recent call last):
>   File "Client1.py", line 53, in <module>
>     c = ClientChat(serverport)
>   File "Client1.py", line 24, in __init__
>     gui.callGui()
>   File "a:\FedEx\Exp\ClientGui.py", line 37, in callGui
>     sendbutton =Button(f2, width = 5, height = 2, text = "Send", command 
> = C.ClientChat.senddata())
> TypeError: unbound method senddata() must be called with ClientChat 
> instance as first argument (got nothing instead)


This one is easy. You need to initialize a ClientChat instance first. This may 
be as simple as:

command = C.ClientChat().senddata

although I'm not sure if ClientChat requires any arguments.

Note that you call the ClientChat class, to create an instance, but you DON'T 
call the senddata method, since you want to pass the method itself as a 
callback function. The button will call it for you, when needed.



-- 
Steven


From abhishek.vit at gmail.com  Fri Jan 27 23:13:49 2012
From: abhishek.vit at gmail.com (Abhishek Pratap)
Date: Fri, 27 Jan 2012 14:13:49 -0800
Subject: [Tutor] ignoring certain lines while reading through CSV
Message-ID: <CAJbA1KCGLJGHvsFcwwNdoCJTm510HSsjyCB3hHS_4cMn+JVqcw@mail.gmail.com>

Hi Guys

I am wondering if there is a keyword to ignore certain lines ( for eg
lines starting with # ) when I am reading them through stl module csv.

Example code:

input_file = sys.argv[1]
csv.register_dialect('multiplex_info',delimiter=' ')

with open(input_file, 'rb') as fh:
    reader= csv.reader(fh,'multiplex_info')
    for row in reader:
        print row


best,
-Abhi

From joel.goldstick at gmail.com  Fri Jan 27 23:42:14 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Fri, 27 Jan 2012 17:42:14 -0500
Subject: [Tutor] ignoring certain lines while reading through CSV
In-Reply-To: <CAJbA1KCGLJGHvsFcwwNdoCJTm510HSsjyCB3hHS_4cMn+JVqcw@mail.gmail.com>
References: <CAJbA1KCGLJGHvsFcwwNdoCJTm510HSsjyCB3hHS_4cMn+JVqcw@mail.gmail.com>
Message-ID: <CAPM-O+yXHko9+6yiP4LBue+CkHudOTKZ5H7CUS0ErMFs5qPf6w@mail.gmail.com>

On Fri, Jan 27, 2012 at 5:13 PM, Abhishek Pratap <abhishek.vit at gmail.com> wrote:
> Hi Guys
>
> I am wondering if there is a keyword to ignore certain lines ( for eg
> lines starting with # ) when I am reading them through stl module csv.
>
> Example code:
>
> input_file = sys.argv[1]
> csv.register_dialect('multiplex_info',delimiter=' ')
>
> with open(input_file, 'rb') as fh:
> ? ?reader= csv.reader(fh,'multiplex_info')
> ? ?for row in reader:
> ? ? ? ?print row
>
>
> best,
> -Abhi
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

You could look up the docs for csv.reader, but if there isn't, in your
for loop you can use row[0].startswith('"#")  to check if your line
starts with #.
Can you show what the row looks like?

-- 
Joel Goldstick

From abhishek.vit at gmail.com  Fri Jan 27 23:48:45 2012
From: abhishek.vit at gmail.com (Abhishek Pratap)
Date: Fri, 27 Jan 2012 14:48:45 -0800
Subject: [Tutor] ignoring certain lines while reading through CSV
In-Reply-To: <CAPM-O+yXHko9+6yiP4LBue+CkHudOTKZ5H7CUS0ErMFs5qPf6w@mail.gmail.com>
References: <CAJbA1KCGLJGHvsFcwwNdoCJTm510HSsjyCB3hHS_4cMn+JVqcw@mail.gmail.com>
	<CAPM-O+yXHko9+6yiP4LBue+CkHudOTKZ5H7CUS0ErMFs5qPf6w@mail.gmail.com>
Message-ID: <CAJbA1KDrzEmN2trenGYA5B_7TJJeZszt6wOJEvpQNYPJS0Hx-g@mail.gmail.com>

Hi Joel

Here is a sample

['1', 'AAAAAAA', '4344', '0.001505'] : want to keep this one

['#', 'AAAAAAA', '4344', '0.001505'] : and throw this one


You are right I am checking after parsing. I dint find an option in
csv.reader to ignore lines.

-Abhi





On Fri, Jan 27, 2012 at 2:42 PM, Joel Goldstick
<joel.goldstick at gmail.com> wrote:
> On Fri, Jan 27, 2012 at 5:13 PM, Abhishek Pratap <abhishek.vit at gmail.com> wrote:
>> Hi Guys
>>
>> I am wondering if there is a keyword to ignore certain lines ( for eg
>> lines starting with # ) when I am reading them through stl module csv.
>>
>> Example code:
>>
>> input_file = sys.argv[1]
>> csv.register_dialect('multiplex_info',delimiter=' ')
>>
>> with open(input_file, 'rb') as fh:
>> ? ?reader= csv.reader(fh,'multiplex_info')
>> ? ?for row in reader:
>> ? ? ? ?print row
>>
>>
>> best,
>> -Abhi
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> You could look up the docs for csv.reader, but if there isn't, in your
> for loop you can use row[0].startswith('"#") ?to check if your line
> starts with #.
> Can you show what the row looks like?
>
> --
> Joel Goldstick

From joel.goldstick at gmail.com  Sat Jan 28 00:04:15 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Fri, 27 Jan 2012 18:04:15 -0500
Subject: [Tutor] ignoring certain lines while reading through CSV
In-Reply-To: <CAJbA1KDrzEmN2trenGYA5B_7TJJeZszt6wOJEvpQNYPJS0Hx-g@mail.gmail.com>
References: <CAJbA1KCGLJGHvsFcwwNdoCJTm510HSsjyCB3hHS_4cMn+JVqcw@mail.gmail.com>
	<CAPM-O+yXHko9+6yiP4LBue+CkHudOTKZ5H7CUS0ErMFs5qPf6w@mail.gmail.com>
	<CAJbA1KDrzEmN2trenGYA5B_7TJJeZszt6wOJEvpQNYPJS0Hx-g@mail.gmail.com>
Message-ID: <CAPM-O+xkcviiuvigh4i=S4_kxeYXFds22DAKNfTdG6EjpM64yg@mail.gmail.com>

On Fri, Jan 27, 2012 at 5:48 PM, Abhishek Pratap <abhishek.vit at gmail.com> wrote:
> Hi Joel
>
> Here is a sample
>
> ['1', 'AAAAAAA', '4344', '0.001505'] : want to keep this one
>
> ['#', 'AAAAAAA', '4344', '0.001505'] : and throw this one

Ok, so you are getting single quotes around your data.  So do
row[0].startswith("#") to test your row.
You may be able to test for row[0]=="#" if you always get only the #
in the first position of the row.
>
>
> You are right I am checking after parsing. I dint find an option in
> csv.reader to ignore lines.
>
> -Abhi
>
>
>
>
>
> On Fri, Jan 27, 2012 at 2:42 PM, Joel Goldstick
> <joel.goldstick at gmail.com> wrote:
>> On Fri, Jan 27, 2012 at 5:13 PM, Abhishek Pratap <abhishek.vit at gmail.com> wrote:
>>> Hi Guys
>>>
>>> I am wondering if there is a keyword to ignore certain lines ( for eg
>>> lines starting with # ) when I am reading them through stl module csv.
>>>
>>> Example code:
>>>
>>> input_file = sys.argv[1]
>>> csv.register_dialect('multiplex_info',delimiter=' ')
>>>
>>> with open(input_file, 'rb') as fh:
>>> ? ?reader= csv.reader(fh,'multiplex_info')
>>> ? ?for row in reader:
>>> ? ? ? ?print row
>>>
>>>
>>> best,
>>> -Abhi
>>> _______________________________________________
>>> Tutor maillist ?- ?Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>> You could look up the docs for csv.reader, but if there isn't, in your
>> for loop you can use row[0].startswith('"#") ?to check if your line
>> starts with #.
>> Can you show what the row looks like?
>>
-- 
Joel Goldstick

From abhishek.vit at gmail.com  Sat Jan 28 00:18:10 2012
From: abhishek.vit at gmail.com (Abhishek Pratap)
Date: Fri, 27 Jan 2012 15:18:10 -0800
Subject: [Tutor] ignoring certain lines while reading through CSV
In-Reply-To: <CAPM-O+xkcviiuvigh4i=S4_kxeYXFds22DAKNfTdG6EjpM64yg@mail.gmail.com>
References: <CAJbA1KCGLJGHvsFcwwNdoCJTm510HSsjyCB3hHS_4cMn+JVqcw@mail.gmail.com>
	<CAPM-O+yXHko9+6yiP4LBue+CkHudOTKZ5H7CUS0ErMFs5qPf6w@mail.gmail.com>
	<CAJbA1KDrzEmN2trenGYA5B_7TJJeZszt6wOJEvpQNYPJS0Hx-g@mail.gmail.com>
	<CAPM-O+xkcviiuvigh4i=S4_kxeYXFds22DAKNfTdG6EjpM64yg@mail.gmail.com>
Message-ID: <CAJbA1KCm8cbHPDM3U1tYPhvWmcqHBdanCyuzst3C-sO9zq_LnA@mail.gmail.com>

Thansk Joel. Thats exactly what I am doing.

-A

On Fri, Jan 27, 2012 at 3:04 PM, Joel Goldstick
<joel.goldstick at gmail.com> wrote:
> On Fri, Jan 27, 2012 at 5:48 PM, Abhishek Pratap <abhishek.vit at gmail.com> wrote:
>> Hi Joel
>>
>> Here is a sample
>>
>> ['1', 'AAAAAAA', '4344', '0.001505'] : want to keep this one
>>
>> ['#', 'AAAAAAA', '4344', '0.001505'] : and throw this one
>
> Ok, so you are getting single quotes around your data. ?So do
> row[0].startswith("#") to test your row.
> You may be able to test for row[0]=="#" if you always get only the #
> in the first position of the row.
>>
>>
>> You are right I am checking after parsing. I dint find an option in
>> csv.reader to ignore lines.
>>
>> -Abhi
>>
>>
>>
>>
>>
>> On Fri, Jan 27, 2012 at 2:42 PM, Joel Goldstick
>> <joel.goldstick at gmail.com> wrote:
>>> On Fri, Jan 27, 2012 at 5:13 PM, Abhishek Pratap <abhishek.vit at gmail.com> wrote:
>>>> Hi Guys
>>>>
>>>> I am wondering if there is a keyword to ignore certain lines ( for eg
>>>> lines starting with # ) when I am reading them through stl module csv.
>>>>
>>>> Example code:
>>>>
>>>> input_file = sys.argv[1]
>>>> csv.register_dialect('multiplex_info',delimiter=' ')
>>>>
>>>> with open(input_file, 'rb') as fh:
>>>> ? ?reader= csv.reader(fh,'multiplex_info')
>>>> ? ?for row in reader:
>>>> ? ? ? ?print row
>>>>
>>>>
>>>> best,
>>>> -Abhi
>>>> _______________________________________________
>>>> Tutor maillist ?- ?Tutor at python.org
>>>> To unsubscribe or change subscription options:
>>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>> You could look up the docs for csv.reader, but if there isn't, in your
>>> for loop you can use row[0].startswith('"#") ?to check if your line
>>> starts with #.
>>> Can you show what the row looks like?
>>>
> --
> Joel Goldstick

From marc.tompkins at gmail.com  Sat Jan 28 02:35:39 2012
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Fri, 27 Jan 2012 17:35:39 -0800
Subject: [Tutor] compile time calculator
In-Reply-To: <SNT130-W27F5CD1F9F21EB56ECD8D3A48E0@phx.gbl>
References: <SNT130-W27F5CD1F9F21EB56ECD8D3A48E0@phx.gbl>
Message-ID: <CAKK8jXZ6rWd35bGR5idFQGJ1ofoFr1o-SNEJ4NQHNkAcCBVVAA@mail.gmail.com>

On Fri, Jan 27, 2012 at 7:46 AM, Surya K <suryak at live.com> wrote:

>  Hi,
>
> I want to calculate compile time for my puzzles.
>

Since nobody else has mentioned it yet...
http://xkcd.com/303/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120127/31c07282/attachment-0001.html>

From mjolewis at gmail.com  Sat Jan 28 06:55:43 2012
From: mjolewis at gmail.com (Michael Lewis)
Date: Fri, 27 Jan 2012 21:55:43 -0800
Subject: [Tutor] Rounding Error
Message-ID: <CAE5MWfWwH_rGoLNOp+8n=PBmeiG7XVZR2dO1fHJRXesWdmrzSw@mail.gmail.com>

I am trying to round a float to two decimals, but I am getting the
following error:

Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    PaintingProject()
  File "C:/Python27/Homework/Labs/Lab 03_5.py", line 42, in PaintingProject
    print 'That will cost you $%f.' %(round(5.6523),2)
TypeError: not all arguments converted during string formatting

Basically, I am writing a program to ask a user how many square feet they
need to paint. I then calculate how many cans of paint they need and will
also show the total purchase price. I've tried this two ways, and the first
way I am semi-successful meaning that my output is rounding but it displays
a number of zero's after the number rounds. The second way, I am getting
the error mentioned above. What am I doing wrong? How can I do this better?
(note, for the sake of brevity, I only show the code in question and not
the whole program).

        total = PRICE_PER_CAN * cans + (PRICE_PER_CAN * cans * TAX)
        total = round(total,2)
        print 'For %d square feet, you\'ll need %d cans of paint.'
%(square_feet, cans)
        print 'That will cost you $%f.' %(total)



        total = PRICE_PER_CAN * cans + (PRICE_PER_CAN * cans * TAX)
        print 'For %d square feet, you\'ll need %d cans of paint.'
%(square_feet, cans)
        print 'That will cost you $%f.' %(round(total),2)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120127/268949e4/attachment.html>

From mjolewis at gmail.com  Sat Jan 28 07:01:34 2012
From: mjolewis at gmail.com (Michael Lewis)
Date: Fri, 27 Jan 2012 22:01:34 -0800
Subject: [Tutor] Rounding Error
In-Reply-To: <CAE5MWfWwH_rGoLNOp+8n=PBmeiG7XVZR2dO1fHJRXesWdmrzSw@mail.gmail.com>
References: <CAE5MWfWwH_rGoLNOp+8n=PBmeiG7XVZR2dO1fHJRXesWdmrzSw@mail.gmail.com>
Message-ID: <CAE5MWfULNXMTxGZRjAJ3Mvg3cszd1JpMUEChLZsOC4n7PUFmSQ@mail.gmail.com>

Update

I am trying to round a float to two decimals.
>
> Basically, I am writing a program to ask a user how many square feet they
> need to paint. I then calculate how many cans of paint they need and will
> also show the total purchase price. I've tried this two ways, and both ways
> I am semi-successful meaning that my output is rounding but it displays a
> number of zero's after the number rounds. How can I make the zero's stop
> displaying?
>



>         total = PRICE_PER_CAN * cans + (PRICE_PER_CAN * cans * TAX)
>         total = round(total,2)
>         print 'For %d square feet, you\'ll need %d cans of paint.'
> %(square_feet, cans)
>         print 'That will cost you $%f.' %(total)
>
>
>
>         total = PRICE_PER_CAN * cans + (PRICE_PER_CAN * cans * TAX)
>         print 'For %d square feet, you\'ll need %d cans of paint.'
> %(square_feet, cans)
>         print 'That will cost you $%f.' %round(total,2)
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120127/ca11af15/attachment.html>

From steve at pearwood.info  Sat Jan 28 07:20:20 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 28 Jan 2012 17:20:20 +1100
Subject: [Tutor] Rounding Error
In-Reply-To: <CAE5MWfWwH_rGoLNOp+8n=PBmeiG7XVZR2dO1fHJRXesWdmrzSw@mail.gmail.com>
References: <CAE5MWfWwH_rGoLNOp+8n=PBmeiG7XVZR2dO1fHJRXesWdmrzSw@mail.gmail.com>
Message-ID: <4F2393A4.1010200@pearwood.info>

Michael Lewis wrote:
> I am trying to round a float to two decimals, but I am getting the
> following error:
> 
> Traceback (most recent call last):
>   File "<pyshell#23>", line 1, in <module>
>     PaintingProject()
>   File "C:/Python27/Homework/Labs/Lab 03_5.py", line 42, in PaintingProject
>     print 'That will cost you $%f.' %(round(5.6523),2)
> TypeError: not all arguments converted during string formatting

> 
> Basically, I am writing a program to ask a user how many square feet they
> need to paint.

All this is irrelevant to your problem. Read the error message: it says that 
you have more arguments than expected when doing the string formatting. 
round() doesn't enter into it. You can get the same error if you do this:

print 'That will cost you $%f.' % (5.6523, 2)

You have one % target in the string, but two numbers trying to fit into it, 
and Python refuses to guess if you want to use 5.6523 or 2.

And that should give you the clue you need to solve the problem, which brings 
it back to round(). You want to round to two decimal places, but you don't put 
the 2 inside the call to round. You have:

(round(5.6523), 2)

which gives you two numbers: (6.0, 2)

but what you actually want is:

round(5.6523, 2)

which gives you the number you want, 5.65.

And finally, we come all the way back to the beginning again and say That's 
not the right way to do it! Don't round the number *outside* of the string 
formatting, get the string formatting to do it for you:

print 'That will cost you $%.2f.' % 5.6523

will give you the result you want.




-- 
Steven


From jeanpierreda at gmail.com  Sat Jan 28 08:06:33 2012
From: jeanpierreda at gmail.com (Devin Jeanpierre)
Date: Sat, 28 Jan 2012 02:06:33 -0500
Subject: [Tutor] Rounding Error
In-Reply-To: <4F2393A4.1010200@pearwood.info>
References: <CAE5MWfWwH_rGoLNOp+8n=PBmeiG7XVZR2dO1fHJRXesWdmrzSw@mail.gmail.com>
	<4F2393A4.1010200@pearwood.info>
Message-ID: <CABicbJKMTbNHybbF6GRog4DPUt1CaTZiDw4oGo0EgLMS1JuQcQ@mail.gmail.com>

On Sat, Jan 28, 2012 at 1:20 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> And finally, we come all the way back to the beginning again and say That's
> not the right way to do it! Don't round the number *outside* of the string
> formatting, get the string formatting to do it for you:

Reason being because repr(round(0.1, 2)) != '0.1' (on older Pythons).
String formatting does the right thing.

Also don't use floats for currency, they can attract rounding errors
and can't represent many common amounts with 100% precision, the way a
Decimal or Fraction can (see decimal, fractions modules). For example,
it can't represent 0.1 exactly, thus leading to the above situation.

-- Devin

From alan.gauld at btinternet.com  Sat Jan 28 09:03:19 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 28 Jan 2012 08:03:19 +0000
Subject: [Tutor] Rounding Error
In-Reply-To: <CAE5MWfWwH_rGoLNOp+8n=PBmeiG7XVZR2dO1fHJRXesWdmrzSw@mail.gmail.com>
References: <CAE5MWfWwH_rGoLNOp+8n=PBmeiG7XVZR2dO1fHJRXesWdmrzSw@mail.gmail.com>
Message-ID: <jg0a47$vqd$1@dough.gmane.org>

On 28/01/12 05:55, Michael Lewis wrote:
> I am trying to round a float to two decimals, but I am getting the
> following error:
>
> Traceback (most recent call last):
>    File "<pyshell#23>", line 1, in <module>
>      PaintingProject()
>    File "C:/Python27/Homework/Labs/Lab 03_5.py", line 42, in PaintingProject
>      print 'That will cost you $%f.' %(round(5.6523),2)
> TypeError: not all arguments converted during string formatting
>

In general rounding the float is the wrong approach, instead you want to 
display the float with two decimal places. You can do that with options 
in the format string. Try:

       print 'That will cost you $%4.2f.' % 5.6523)

The %4.2f says use 4 characters with 2 of them after the decimal point.
There are many other options you can use to tweak the display, read the 
string formatting documents...

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


From opentechblogger at gmail.com  Sat Jan 28 11:02:53 2012
From: opentechblogger at gmail.com (t4 techno)
Date: Sat, 28 Jan 2012 15:32:53 +0530
Subject: [Tutor] Python with HTML
Message-ID: <CAJgZNT2A00hL+UHAjijQNZx3pTy-u3gBJz68SqeGhH5wTcas1A@mail.gmail.com>

hi everyone,

I want to make a web page which has to include some python script and html
tags as well, am not getting how to do that .
I searched some articles but cant understand them .
is there anything like linking an external html file into python script ?

Can u please help for same
waiting for your instructions or some links that can help me

Regards
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120128/3a79f765/attachment-0001.html>

From suryak at live.com  Sat Jan 28 14:50:34 2012
From: suryak at live.com (Surya K)
Date: Sat, 28 Jan 2012 19:20:34 +0530
Subject: [Tutor] compile time calculator
In-Reply-To: <CAKK8jXZ6rWd35bGR5idFQGJ1ofoFr1o-SNEJ4NQHNkAcCBVVAA@mail.gmail.com>
References: <SNT130-W27F5CD1F9F21EB56ECD8D3A48E0@phx.gbl>,
	<CAKK8jXZ6rWd35bGR5idFQGJ1ofoFr1o-SNEJ4NQHNkAcCBVVAA@mail.gmail.com>
Message-ID: <SNT130-W36AA8811852A9943158F2EA48F0@phx.gbl>




Date: Fri, 27 Jan 2012 17:35:39 -0800
Subject: Re: [Tutor] compile time calculator
From: marc.tompkins at gmail.com
To: suryak at live.com
CC: tutor at python.org

On Fri, Jan 27, 2012 at 7:46 AM, Surya K <suryak at live.com> wrote:





Hi,
I want to calculate compile time for my puzzles. 
Since nobody else has mentioned it yet...
http://xkcd.com/303/


Well, using python documentation, I did this..
(calculating execution time).
def main():## This is my whole puzzle code...

    fobj_ip = open('D:/code/py/input.txt', 'r')    fobj_op = open('D:/code/py/output.txt','w')
    line=1    for eachLine in fobj_ip:        if line>1:            fobj_op.write ("Case #%d: %d\n" %(line-1, the_count(eachLine) ) )        line+=1
    pass
if __name__ == '__main__':    from timeit import Timer    main()    t = Timer("main()")    print t.timeit()

This is showing the following output
10000000 loops, best of 3: 0.0612 usec per loop
(This is repeating...)
So, what exactly is 0.0612 usec per loop, is that execution time of my whole program??If, how do I calculate it in seconds.

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

From suryak at live.com  Sat Jan 28 19:14:15 2012
From: suryak at live.com (Surya K)
Date: Sat, 28 Jan 2012 23:44:15 +0530
Subject: [Tutor] how to convert usec/pass to seconds
Message-ID: <SNT130-W441C6D827236D8D44D048EA48F0@phx.gbl>


I am actually using a activestate wrapper for calculating execution time of my program.

This is the code 
#!/usr/bin/python# A simple wrapper for the timeit module.import timeit
def Timeit(func,number=10000,module="__main__"):    """ A wrapper which can    be used to time any function """
    name = func.__name__    t = timeit.Timer("%s()"%name, "from %s import %s" % (module, name))    return "%.2f usec/pass" % (1000000*t.timeit(number=number)/number)
if __name__=="__main__":
    from program import*
    # Using wrapper    print Timeit(main)    # Directly using timeit    t = timeit.Timer("main()", "from __main__ import main")    print "%.2f usec/pass" % (1000000*t.timeit(number=10000)/10000)

So, this module is showing my execution time in usec/pass.
I tested it for a puzzle and that showed me around 1385.33 usec/sec..However, as its from facebook hackers cup where I got a penalty time of 28.32.00 (not exactly, forgot).. 
what units facebook was following.. If I had to change those usec/pass units to seconds, what I have to use.
can anyone tell me?


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

From evert.rol at gmail.com  Sat Jan 28 22:17:02 2012
From: evert.rol at gmail.com (Evert Rol)
Date: Sat, 28 Jan 2012 22:17:02 +0100
Subject: [Tutor] compile time calculator
In-Reply-To: <SNT130-W36AA8811852A9943158F2EA48F0@phx.gbl>
References: <SNT130-W27F5CD1F9F21EB56ECD8D3A48E0@phx.gbl>,
	<CAKK8jXZ6rWd35bGR5idFQGJ1ofoFr1o-SNEJ4NQHNkAcCBVVAA@mail.gmail.com>
	<SNT130-W36AA8811852A9943158F2EA48F0@phx.gbl>
Message-ID: <7B9401BF-EBC9-4D3A-A073-480EC5D37766@gmail.com>

> Well, using python documentation, I did this..
> 
> (calculating execution time).
> 
> def main():
> ## This is my whole puzzle code...
> 
> 
>     fobj_ip = open('D:/code/py/input.txt', 'r')
>     fobj_op = open('D:/code/py/output.txt','w')
> 
>     line=1
>     for eachLine in fobj_ip:
>         if line>1:
>             fobj_op.write ("Case #%d: %d\n" %(line-1, the_count(eachLine) ) )
>         line+=1
> 
>     pass
> 
> if __name__ == '__main__':
>     from timeit import Timer
>     main()
>     t = Timer("main()")

This, in my experience, causes problems: timeit doesn't run your main(), it runs its own timeit.main() function.
Try renaming main() to test(), and see if things still work.

>     print t.timeit()
> 
> 
> This is showing the following output
> 10000000 loops, best of 3: 0.0612 usec per loop
> 
> (This is repeating...)
> 
> So, what exactly is 0.0612 usec per loop, is that execution time of my whole program??
> If, how do I calculate it in seconds.

As far as I'm aware, timeit runs the function in your Timer class (the 'main' function) 10000000 times. So it doesn't run the complete program, but assuming the main function is the entry point of the program, that's very near.
The 10000000 times is the loop; timeit will measure the total time spent looping 10000000 times through your main function, then average that. 
It does this procedure 3 times, then takes the best value of three (the values could be very different, if your computer is otherwise occupied that slows down the execution of your program; hence best of three).
The 10000000 and 3 are the default values, by the way. See the timeit.Timer.repeat documentation.
So in the end, you have the average duration of a single execution of the main function, assuming the best circumstances ('best out of 3').

The usec stands for microseconds; it should actually be ?s. One microsecond is 1 millionth of a second, so 0.0612 usec would be 0.0000000612 seconds for one executiong of main().


Hope that helps,

  Evert


From steve at pearwood.info  Sat Jan 28 23:48:29 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 29 Jan 2012 09:48:29 +1100
Subject: [Tutor] how to convert usec/pass to seconds
In-Reply-To: <SNT130-W441C6D827236D8D44D048EA48F0@phx.gbl>
References: <SNT130-W441C6D827236D8D44D048EA48F0@phx.gbl>
Message-ID: <4F247B3D.7070503@pearwood.info>

Surya K wrote:
> I am actually using a activestate wrapper for calculating execution time of my program.
[...]
> I tested it for a puzzle and that showed me around 1385.33 usec/sec..However, as its from facebook hackers cup where I got a penalty time of 28.32.00 (not exactly, forgot).. 
> what units facebook was following.. If I had to change those usec/pass units to seconds, what I have to use.
> can anyone tell me?

1 second = 1000000 microseconds

Strictly speaking, it should be ?s rather than usec.

http://en.wikipedia.org/wiki/SI_prefix#List_of_SI_prefixes


-- 
Steven


From xting at sbcglobal.net  Sun Jan 29 04:52:00 2012
From: xting at sbcglobal.net (Alan Ting)
Date: Sat, 28 Jan 2012 19:52:00 -0800 (PST)
Subject: [Tutor] How to split something?
Message-ID: <1327809120.29347.YahooMailClassic@web180007.mail.gq1.yahoo.com>

Hello,
How do I get the characters to separate?
This is what I did.
def personalNote(name):
??? 'Print a personalized love note'
??? x = (name)
??? print (x + ", I love you so.")
??? print ("You brighten my day.")
??? print ("Oh, " + x + "!")
??? print ("I wish you could be with me always")

Write a function personalNote() that takes as 
	input a name (as a string) and prints a love note as follows:
		
			
				>>> personalNote('Joon')
			
			
				Joon, I love you so.
			
			
				You brighten my day.
			
			
				Oh, J O O N !
			
			
				I wish you could be with me always.
			
			
				But alas, Joon, you must stay away.
			
			
				>>> personalNote('Djengo')
			
			
				Djengo, I love you so.
			
			
				You brighten my day.
			
			
				Oh, D J E N G O!
			
			
				I wish you could be with me always.

			
			
				But alas, Djengo, you must stay away.

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

From steve at pearwood.info  Sun Jan 29 05:15:54 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 29 Jan 2012 15:15:54 +1100
Subject: [Tutor] How to split something?
In-Reply-To: <1327809120.29347.YahooMailClassic@web180007.mail.gq1.yahoo.com>
References: <1327809120.29347.YahooMailClassic@web180007.mail.gq1.yahoo.com>
Message-ID: <4F24C7FA.8060706@pearwood.info>

Alan Ting wrote:
> Hello,
> How do I get the characters to separate?

It isn't clear what you mean. Do you mean this?

"JOON" => "J O O N"


If so:

' '.join('JOON')

will do it.


-- 
Steven

From steve at pearwood.info  Sun Jan 29 05:51:45 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 29 Jan 2012 15:51:45 +1100
Subject: [Tutor] How to split something?
In-Reply-To: <1327809120.29347.YahooMailClassic@web180007.mail.gq1.yahoo.com>
References: <1327809120.29347.YahooMailClassic@web180007.mail.gq1.yahoo.com>
Message-ID: <4F24D061.6030809@pearwood.info>

Alan Ting wrote:
> Hello,
> How do I get the characters to separate?
> This is what I did.
> def personalNote(name):
>     'Print a personalized love note'
>     x = (name)

Oh, I forgot to mention... the line x = (name) is utterly pointless. Instead 
of wasting time with x=name, just use name everywhere your code uses x.



-- 
Steven

From evert.rol at gmail.com  Sun Jan 29 09:41:49 2012
From: evert.rol at gmail.com (Evert Rol)
Date: Sun, 29 Jan 2012 09:41:49 +0100
Subject: [Tutor] Python with HTML
In-Reply-To: <CAJgZNT2A00hL+UHAjijQNZx3pTy-u3gBJz68SqeGhH5wTcas1A@mail.gmail.com>
References: <CAJgZNT2A00hL+UHAjijQNZx3pTy-u3gBJz68SqeGhH5wTcas1A@mail.gmail.com>
Message-ID: <8826F72F-A356-40AE-A833-2FA77023F6C0@gmail.com>

> hi everyone,
> 
> I want to make a web page which has to include some python script and html tags as well, am not getting how to do that . 
> I searched some articles but cant understand them .
> is there anything like linking an external html file into python script ?
> 
> Can u please help for same 
> waiting for your instructions or some links that can help me

Not sure what you want. Do you want a HTML page that includes a Python script for the more dynamic parts?
In that case: that won't work. Java (ecma)script is the de facto standard for this. 
You can try and compile Python to javascript using eg Pyjamas (http://pyjs.org/).

If you want your Python script to generate HTML, you can just write out the necessary code using print statements or to a file.

Which articles did you search for, and what did you not understand?

  Evert


From ian.douglas at iandouglas.com  Sun Jan 29 09:58:04 2012
From: ian.douglas at iandouglas.com (ian douglas)
Date: Sun, 29 Jan 2012 00:58:04 -0800
Subject: [Tutor] Python with HTML
In-Reply-To: <CAJgZNT2A00hL+UHAjijQNZx3pTy-u3gBJz68SqeGhH5wTcas1A@mail.gmail.com>
References: <CAJgZNT2A00hL+UHAjijQNZx3pTy-u3gBJz68SqeGhH5wTcas1A@mail.gmail.com>
Message-ID: <CAFNSOgUgArH9Qb-+_nOkwZBvx6ehwvv5Ohzx1m_iEto3jDw+xw@mail.gmail.com>

If you're hoping for something like PHP that can be parsed inline with
html, you're out of luck. It's also bad design to mix business logic with
your presentation layer.

You might want to look into some frameworks like django to help you along.
On Jan 28, 2012 2:04 AM, "t4 techno" <opentechblogger at gmail.com> wrote:

> hi everyone,
>
> I want to make a web page which has to include some python script and html
> tags as well, am not getting how to do that .
> I searched some articles but cant understand them .
> is there anything like linking an external html file into python script ?
>
> Can u please help for same
> waiting for your instructions or some links that can help me
>
> Regards
>
> _______________________________________________
> 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/20120129/9eda79d1/attachment.html>

From steve at pearwood.info  Sun Jan 29 11:02:27 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 29 Jan 2012 21:02:27 +1100
Subject: [Tutor] Python with HTML
In-Reply-To: <8826F72F-A356-40AE-A833-2FA77023F6C0@gmail.com>
References: <CAJgZNT2A00hL+UHAjijQNZx3pTy-u3gBJz68SqeGhH5wTcas1A@mail.gmail.com>
	<8826F72F-A356-40AE-A833-2FA77023F6C0@gmail.com>
Message-ID: <4F251933.8030009@pearwood.info>

Evert Rol wrote:
>> hi everyone,
>>
>> I want to make a web page which has to include some python script and html tags as well, am not getting how to do that . 
>> I searched some articles but cant understand them .
>> is there anything like linking an external html file into python script ?
>>
>> Can u please help for same 
>> waiting for your instructions or some links that can help me
> 
> Not sure what you want. Do you want a HTML page that includes a Python script for the more dynamic parts?
> In that case: that won't work. Java (ecma)script is the de facto standard for this. 


While Javascript is the de facto standard for client-side scripting, it is 
possible to use Python. But you shouldn't: Python is not designed with the 
sort of sand-boxing and security needed to run untrusted code over the 
Internet. But if you only care about running code within your own trusted 
intranet, it should be perfectly doable.

http://bytes.com/topic/python/answers/45528-python-client-side-browser-script-language

A better idea may be to use a templating engine, server-side Python, e.g. 
using Django, CherryPy, or similar, or use Pyjamas to convert Python to 
Javascript.

http://warp.byu.edu/site/content/813



-- 
Steven

From zepangolin at gmail.com  Sun Jan 29 12:18:54 2012
From: zepangolin at gmail.com (P.)
Date: Sun, 29 Jan 2012 12:18:54 +0100
Subject: [Tutor] Python with HTML
In-Reply-To: <4F251933.8030009@pearwood.info>
References: <CAJgZNT2A00hL+UHAjijQNZx3pTy-u3gBJz68SqeGhH5wTcas1A@mail.gmail.com>
	<8826F72F-A356-40AE-A833-2FA77023F6C0@gmail.com>
	<4F251933.8030009@pearwood.info>
Message-ID: <CAJmJHtB200mQFhowbR4NCjW47yiaXE5g6pck0ChLRSnZDQphnQ@mail.gmail.com>

>
> I want to make a web page which has to include some python script and html
>> tags as well, am not getting how to do that .
>>
> **

Hi,
Maybe a quick and small solution is here :
http://karrigell.sourceforge.net/en/index.html
It doesn't seem to be a very living project, but it can be a solution for
you, depending of what you want.

There is also python integration in Apache : http://www.modpython.org/

And finaly a more more (maybe too much) powerfull solution is maybe Zope :
http://www.zope.org/

Regards,
Patrice
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120129/140f901b/attachment.html>

From stefan_ml at behnel.de  Sun Jan 29 13:17:54 2012
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sun, 29 Jan 2012 13:17:54 +0100
Subject: [Tutor] Python with HTML
In-Reply-To: <CAJgZNT2A00hL+UHAjijQNZx3pTy-u3gBJz68SqeGhH5wTcas1A@mail.gmail.com>
References: <CAJgZNT2A00hL+UHAjijQNZx3pTy-u3gBJz68SqeGhH5wTcas1A@mail.gmail.com>
Message-ID: <jg3ddi$3gu$1@dough.gmane.org>

t4 techno, 28.01.2012 11:02:
> I want to make a web page which has to include some python script and html
> tags as well, am not getting how to do that .
> I searched some articles but cant understand them .
> is there anything like linking an external html file into python script ?
> 
> Can u please help for same
> waiting for your instructions or some links that can help me

As others have pointed out, your request is not very clear. I agree that
client side Python in a browser is not the best approach, but if your
question is about server side HTML generation from Python, you should
either look at one of the web frameworks (a couple of them were already
mentioned), or use a templating engine. There are plenty of them for
Python, here is a list:

http://wiki.python.org/moin/Templating

There are also plenty of web frameworks, BTW. They are better than plain
templating engines when your data becomes non-trivial and comes from a
database etc.

Depending on what you actually want to do (note that you only said *how*
you want to do it, not *what* you want to do), you should also look at
content management systems like Plone.

Hope that helps,

Stefan


From geonyoro at gmail.com  Sun Jan 29 16:14:41 2012
From: geonyoro at gmail.com (George Nyoro)
Date: Sun, 29 Jan 2012 18:14:41 +0300
Subject: [Tutor] Deleting an object
Message-ID: <CAM71YVHQkup5ghV56mLpLEzK+15AKmb8-O2ibCnv8zoQSF3nQg@mail.gmail.com>

Hi all,

       Last time I tried to post a question regarding this, I was asked to
clarify. Okay so here it is. There is a class called Table and objects are
just tables, you know, matrices, holding different types of data. Thing is,
I want to provide a method where one can delete the object and then if the
user tries using a variable to access a certain method or attributes, he
gets an error. Let me give an example;

class Table:

def delete_this(self):

#code to delete this object or assign it null or None

pass

def do_something(self):

pass

x=Table()

x.delete_this()

#at this point, I want such that if I try to use x I get some sort of error
e.g.

x.do_something()

#Error: x is definitely not an object anymore


 All clear?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120129/5b3381f5/attachment.html>

From hugo.yoshi at gmail.com  Sun Jan 29 16:36:33 2012
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sun, 29 Jan 2012 16:36:33 +0100
Subject: [Tutor] Deleting an object
In-Reply-To: <CAM71YVHQkup5ghV56mLpLEzK+15AKmb8-O2ibCnv8zoQSF3nQg@mail.gmail.com>
References: <CAM71YVHQkup5ghV56mLpLEzK+15AKmb8-O2ibCnv8zoQSF3nQg@mail.gmail.com>
Message-ID: <CAJmBOf=kum2jE1bqg2LzFQSXFMZPmuNptLCmdB81toOKC6+G9A@mail.gmail.com>

On Sun, Jan 29, 2012 at 4:14 PM, George Nyoro <geonyoro at gmail.com> wrote:
> Hi all,
>
> ?????? Last time I tried to post a question regarding this, I was asked to
> clarify. Okay so here it is. There is a class called Table and objects are
> just tables, you know, matrices, holding different types of data. Thing is,
> I want to provide a method where one can delete the object and then if the
> user tries using a variable to access a certain method or attributes, he
> gets an error. Let me give an example;
>
> class Table:
>
> def delete_this(self):
>
> #code to delete this object or assign it null or None
>
> pass
>
> def do_something(self):
>
> pass
>
> x=Table()
>
> x.delete_this()
>
> #at this point, I want such that if I try to use x I get some sort of error
> e.g.
>
> x.do_something()
>
> #Error: x is definitely not an object anymore
>
>
> All clear?
>

__getattribute__ is the closest you'll get to that, e.g. like the
class below. A complete implementation is impossible, since language
builtins bypass even the __getattribute__ method, but as long as you
do not use them you should be fine:

class Table(object):
    def __init__(self):
        self.deleted = False

    def __getattribute__(self, attr):
        if object.__getattribute__(self, 'deleted'):
            raise AttributeError("this object has been deleted")
        return object.__getattribute__(self, attr)

    def __len__(self):
        return 10

    def delete(self):
        self.deleted = True

>>> # the object is still alive, we can access stuff easily
>>> t = Table()
>>> t.deleted
False
>>> t.__len__()
10
>>> t.delete()
>>> # now we cant access anything anymore without raising an error
>>> t.deleted

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    t.deleted
  File "C:\Users\hugo\Downloads\test.py", line 7, in __getattribute__
    raise AttributeError("this object has been deleted")
AttributeError: this object has been deleted
>>> t.__len__()

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    t.__len__()
  File "C:\Users\hugo\Downloads\test.py", line 7, in __getattribute__
    raise AttributeError("this object has been deleted")
AttributeError: this object has been deleted
>>> # unfortunately, the python internals can still access your methods, so len() and things like operators will still work. There is no way around this
>>> len(t)
10
>>>

Of course this method can easily be adapted to restrict access only to
certain methods/attributes.

HTH,
Hugo

From rhettnaxel at gmail.com  Sun Jan 29 16:38:23 2012
From: rhettnaxel at gmail.com (Alexander)
Date: Sun, 29 Jan 2012 10:38:23 -0500
Subject: [Tutor] Deleting an object
In-Reply-To: <CAM71YVHQkup5ghV56mLpLEzK+15AKmb8-O2ibCnv8zoQSF3nQg@mail.gmail.com>
References: <CAM71YVHQkup5ghV56mLpLEzK+15AKmb8-O2ibCnv8zoQSF3nQg@mail.gmail.com>
Message-ID: <CANS6qmDvPCFFWbNYhte=SAtfEeiVOyjTTvjZaoRaC2t_AuFByA@mail.gmail.com>

On Sun, Jan 29, 2012 at 10:14 AM, George Nyoro <geonyoro at gmail.com> wrote:
> Hi all,
> ?????? Last time I tried to post a question regarding this, I was asked to
> clarify. Okay so here it is. There is a class called Table and objects are
> just tables, you know, matrices, holding different types of data. Thing is,
> I want to provide a method where one can delete the object and then if the
> user tries using a variable to access a certain method or attributes, he
> gets an error. Let me give an example;
>
> class Table:
>
> def delete_this(self):
>
> #code to delete this object or assign it null or None
>
> pass
>
> def do_something(self):
>
> pass
>
> x=Table()
>
> x.delete_this()
>
> #at this point, I want such that if I try to use x I get some sort of error
> e.g.
>
> x.do_something()
>
> #Error: x is definitely not an object anymore
>

Hi George. Consider what it means for the object to be deleted. When
one calls the table.delete_this() method what happens? Is a member
variable within the Table object set to None? What members does the
table object have?
-- 
Alexander
7D9C597B

From steve at pearwood.info  Sun Jan 29 16:59:12 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 30 Jan 2012 02:59:12 +1100
Subject: [Tutor] Deleting an object
In-Reply-To: <CAM71YVHQkup5ghV56mLpLEzK+15AKmb8-O2ibCnv8zoQSF3nQg@mail.gmail.com>
References: <CAM71YVHQkup5ghV56mLpLEzK+15AKmb8-O2ibCnv8zoQSF3nQg@mail.gmail.com>
Message-ID: <4F256CD0.5010209@pearwood.info>

George Nyoro wrote:

> class Table:
> def delete_this(self):
> #code to delete this object or assign it null or None
> pass
> def do_something(self):
> pass
> 
> x=Table()
> x.delete_this()
> 
> #at this point, I want such that if I try to use x I get some sort of error
> e.g.
> 
> x.do_something()
> 
> #Error: x is definitely not an object anymore


Instead of "x.delete_this()", why not just say "del x"? Why try to fight 
Python, instead of using the tools Python already gives you?


Objects cannot delete themselves, because they cannot know all the places they 
are referenced.

If you absolutely have to have something like x.delete_this, then try this:


class Table:
     def __init__(self):
         self.alive = True
     def delete_this(self):
         self.alive = False
     def do_something(self):
         if self.alive:
             print("Doing something.")
         else:
             raise TableError("object has been killed")

class TableError(RuntimeError):
     pass


-- 
Steven


From __peter__ at web.de  Sun Jan 29 17:34:12 2012
From: __peter__ at web.de (Peter Otten)
Date: Sun, 29 Jan 2012 17:34:12 +0100
Subject: [Tutor] Deleting an object
References: <CAM71YVHQkup5ghV56mLpLEzK+15AKmb8-O2ibCnv8zoQSF3nQg@mail.gmail.com>
Message-ID: <jg3se3$seo$1@dough.gmane.org>

George Nyoro wrote:

>        Last time I tried to post a question regarding this, I was asked to
> clarify. Okay so here it is. There is a class called Table and objects are
> just tables, you know, matrices, holding different types of data. Thing
> is, I want to provide a method where one can delete the object and then if
> the user tries using a variable to access a certain method or attributes,
> he gets an error. Let me give an example;
> 
> class Table:
>     def delete_this(self):
>         #code to delete this object or assign it null or None
>         pass
> 
>     def do_something(self):
>         pass

> x=Table()
> x.delete_this()
> 
> #at this point, I want such that if I try to use x I get some sort of
> #error
> e.g.
> 
> x.do_something()
> 
> #Error: x is definitely not an object anymore
> 
> 
>  All clear?


>>> class Parrot:
...     def hello(self):
...             print("Hello")
...     def delete_this(self):
...             self.__class__ = DeadParrot
...
>>> class DeadParrot:
...     def __getattr__(self, name):
...             raise Exception("This parrot is no more")
...
>>> p = Parrot()
>>> p.hello()
Hello
>>> p.delete_this()
>>> p.hello()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __getattr__
Exception: This parrot is no more

But I don't think it's a good idea...


From alan.gauld at btinternet.com  Sun Jan 29 19:05:59 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 29 Jan 2012 18:05:59 +0000
Subject: [Tutor] Deleting an object
In-Reply-To: <CAM71YVHQkup5ghV56mLpLEzK+15AKmb8-O2ibCnv8zoQSF3nQg@mail.gmail.com>
References: <CAM71YVHQkup5ghV56mLpLEzK+15AKmb8-O2ibCnv8zoQSF3nQg@mail.gmail.com>
Message-ID: <jg41q7$6lq$1@dough.gmane.org>

On 29/01/12 15:14, George Nyoro wrote:

> data. Thing is, I want to provide a method where one can delete the
> object and then if the user tries using a variable to access a certain
> method or attributes, he gets an error. Let me give an example;

I assume you know about the built in del() function that deletes 
objects? It works on any kind of object.

If you need it to do sometjing fancy(like releasing resources say) you 
can define your own __del__() method that gets called by Python when the 
object is deleted - but you rarely need to do that in Python.

> class Table:
>    def delete_this(self):
>    def do_something(self):

> x=Table()
> x.delete_this()
> #at this point, I want such that if I try to use x I get some sort of
> error e.g.

x = Table()
del(x)

now referencing x or any attribute or method will give a name error.
Here is an example using an int, but any kind of object works:

 >>> x = 42
 >>> x
42
 >>> del(x)
 >>> x
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
 >>>

If thats not what you want you need to come vback and explain what is 
different about your scenario.

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


From rocklearnpython at gmail.com  Sun Jan 29 21:01:47 2012
From: rocklearnpython at gmail.com (Navneet)
Date: Sun, 29 Jan 2012 21:01:47 +0100
Subject: [Tutor] Socket Programming
In-Reply-To: <4F23137C.7060005@pearwood.info>
References: <4F216F9D.3060002@gmail.com> <4F2300C3.4070703@gmail.com>
	<4F23137C.7060005@pearwood.info>
Message-ID: <4F25A5AB.5070903@gmail.com>

On 1/27/2012 10:13 PM, Steven D'Aprano wrote:
> Navneet wrote:
>
>> One more thing I want to add here is, I am trying to create the GUI 
>> based chat server.(Attached the programs.)
>
>
> Please do not send large chunks of code like this, unless asked. 
> Instead, you should try to produce a minimal example that demonstrates 
> the problem. It should be:
>
> * short (avoid code which has nothing to do with the problem)
>
> * self-contained (other people must be able to run it)
>
> * correct (it must actually fail in the way you say it fails)
>
> See here for more: http://sscce.org/
>
>
> In cutting your code down to a minimal example, 9 times out of 10 you 
> will solve your problem yourself, and learn something in the process.
>
>
>> bash-3.1$ python Client1.py
>> Enter the server address:...9009
>> Traceback (most recent call last):
>>   File "Client1.py", line 53, in <module>
>>     c = ClientChat(serverport)
>>   File "Client1.py", line 24, in __init__
>>     gui.callGui()
>>   File "a:\FedEx\Exp\ClientGui.py", line 37, in callGui
>>     sendbutton =Button(f2, width = 5, height = 2, text = "Send", 
>> command = C.ClientChat.senddata())
>> TypeError: unbound method senddata() must be called with ClientChat 
>> instance as first argument (got nothing instead)
>
>
> This one is easy. You need to initialize a ClientChat instance first. 
> This may be as simple as:
>
> command = C.ClientChat().senddata
>
> although I'm not sure if ClientChat requires any arguments.
>
> Note that you call the ClientChat class, to create an instance, but 
> you DON'T call the senddata method, since you want to pass the method 
> itself as a callback function. The button will call it for you, when 
> needed.
>
>
>
Thanks for the clarification and telling me about SSCCE :)

But just a simple thing,,, Can I call a method of another module while 
creating a GUI.

For example
  C = Tk()
.....(Some more lines)
self.sendbutton =Button(self.f2, width = 5, height = 2, text = "Send", 
command = <ANOTHER MODULE>.<METHOD OF THAT MODULE>)
         self.sendbutton.pack(side = LEFT, padx = 10, pady = 10)
.....(Some more lines)
C.mainloop()


Because I am getting stuck in a loop. The client is keep on connecting 
to server without creating a GUI.












From 0101amt at gmail.com  Sun Jan 29 23:28:21 2012
From: 0101amt at gmail.com (amt)
Date: Mon, 30 Jan 2012 00:28:21 +0200
Subject: [Tutor] Why do you have to close files?
In-Reply-To: <jftl79$l3u$1@dough.gmane.org>
References: <CAEQEn03WKcpr+gfUx8O0L7p0TcWAcK2hTHGNTfCaqpWDQsfkJA@mail.gmail.com>
	<jfstu8$m49$1@dough.gmane.org> <jftl79$l3u$1@dough.gmane.org>
Message-ID: <CAEQEn016afJDN+2F_+R-rm2d4MbWGXvN9_ed-AQoNmT=F2VKiQ@mail.gmail.com>

All the replies were very helpful! Thank you very much for helping me out!

From suryak at live.com  Mon Jan 30 06:20:51 2012
From: suryak at live.com (Surya K)
Date: Mon, 30 Jan 2012 10:50:51 +0530
Subject: [Tutor] loop until a keypress
Message-ID: <SNT130-W397E068F9E47ABD82EEA34A48D0@phx.gbl>


I want to run code until a "enter" is pressed. Well, it shouldn't wait for the user to enter "enter"
This is my code:
import msvcrtchr = 0while chr != 'q':     print "my code",     if msvcrt.kbhit():           chr = msvcrt.getch()
This isn't working the way I wanted. When ever I press enter, the loop is starting in a new line and continuing.
I even added "break" statement in "if" block but it isn't workingCan you tell me how to do that?
I am on windows. So, as msvcrt is for windows, I wonder if there is any module that works for both, 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120130/a5996b2a/attachment.html>

From bugcy013 at gmail.com  Mon Jan 30 07:25:12 2012
From: bugcy013 at gmail.com (Ganesh Kumar)
Date: Mon, 30 Jan 2012 11:55:12 +0530
Subject: [Tutor] Help Glade Tutorial.
Message-ID: <CAJzooYc-OaR6JOz9WRJBtv0W6t3L2ZL0dZV+GUyD-yUP9xe-JQ@mail.gmail.com>

Hi Guys,

I am searching for a Glade tutorial, on how to create simple projects Glade
with python

1) design a simple interface in glade
2) use the glade interface to write some really simple application with
python.

I search in goggled i didn't get good tutorials, guide me guys How to start
with Glade.

-Ganesh

Did I learn something today? If not, I wasted it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120130/fec2e0a2/attachment.html>

From cfuller084 at thinkingplanet.net  Mon Jan 30 07:51:58 2012
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Mon, 30 Jan 2012 00:51:58 -0600
Subject: [Tutor] Help Glade Tutorial.
In-Reply-To: <CAJzooYc-OaR6JOz9WRJBtv0W6t3L2ZL0dZV+GUyD-yUP9xe-JQ@mail.gmail.com>
References: <CAJzooYc-OaR6JOz9WRJBtv0W6t3L2ZL0dZV+GUyD-yUP9xe-JQ@mail.gmail.com>
Message-ID: <201201300051.58828.cfuller084@thinkingplanet.net>


Which ones did you look at, and why did you not like them?  Keep in mind that 
Glade is an interface builder, and hasn't got anything much to do with the 
target language, other than requiring there be a libglade library to read the 
XML files.

I actually got started with some articles in Linux Journal, which don't appear 
high on the google search unless you include those terms.  Search for "glade 
tutorial" or "glade linux journal".  Leave Python or pyGTK out of your search 
for now.

You might need a little help with using the XML files glade produces, but 
that's covered in the pyGTK documentation.  It's also in the Linux Journal 
articles.  You can google "pygtk glade" if you need more.

Cheers

On Monday 30 January 2012, Ganesh Kumar wrote:
> Hi Guys,
> 
> I am searching for a Glade tutorial, on how to create simple projects Glade
> with python
> 
> 1) design a simple interface in glade
> 2) use the glade interface to write some really simple application with
> python.
> 
> I search in goggled i didn't get good tutorials, guide me guys How to start
> with Glade.
> 
> -Ganesh
> 
> Did I learn something today? If not, I wasted it.


From __peter__ at web.de  Mon Jan 30 09:10:19 2012
From: __peter__ at web.de (Peter Otten)
Date: Mon, 30 Jan 2012 09:10:19 +0100
Subject: [Tutor] loop until a keypress
References: <SNT130-W397E068F9E47ABD82EEA34A48D0@phx.gbl>
Message-ID: <jg5j97$48b$1@dough.gmane.org>

Surya K wrote:

> I want to run code until a "enter" is pressed. Well, it shouldn't wait for
> the user to enter "enter" This is my code:

This is what it looks like over here:

> import msvcrtchr = 0while chr != 'q':     print "my code",     if
> msvcrt.kbhit():           chr = msvcrt.getch() 

This is what I suppose you wrote:

> import msvcrt
> chr = 0
> while chr != 'q':
>     print "my code",
>     if msvcrt.kbhit():           
>         chr = msvcrt.getch() 


> This isn't working the way
> I wanted. When ever I press enter, the loop is starting in a new line and
> continuing. I even added "break" statement in "if" block but it isn't
> workingCan you tell me how to do that? 

You could make a little experiment. Run

import msvcrt
while True:
    if msvcrt.kbhit():
        print msvcrt.getch()

and then press the 'q' key. What does this little script print? Can you 
apply the newly gained information to your original code?

> I am on windows. So, as msvcrt is
> for windows, I wonder if there is any module that works for both,


From alan.gauld at btinternet.com  Mon Jan 30 09:36:16 2012
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 30 Jan 2012 08:36:16 +0000
Subject: [Tutor] loop until a keypress
In-Reply-To: <SNT130-W397E068F9E47ABD82EEA34A48D0@phx.gbl>
References: <SNT130-W397E068F9E47ABD82EEA34A48D0@phx.gbl>
Message-ID: <jg5kq1$e0a$1@dough.gmane.org>

On 30/01/12 05:20, Surya K wrote:
> I want to run code until a "enter" is pressed. Well, it shouldn't wait
> for the user to enter "enter"
>
> This is my code:
>
> import msvcrt
>
> chr = 0
> while chr != 'q':
> print "my code",
> if msvcrt.kbhit():
> chr = msvcrt.getch()
>

You shouldn't need the kbhit test.
Try just using:

while ky != 'q':
    ky = msvcrt.getch()
    print ky


> I am on windows. So, as msvcrt is for windows, I wonder if there is any
> module that works for both,

Both what?


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


From cwitts at compuscan.co.za  Mon Jan 30 09:49:48 2012
From: cwitts at compuscan.co.za (Christian Witts)
Date: Mon, 30 Jan 2012 10:49:48 +0200
Subject: [Tutor] loop until a keypress
In-Reply-To: <SNT130-W397E068F9E47ABD82EEA34A48D0@phx.gbl>
References: <SNT130-W397E068F9E47ABD82EEA34A48D0@phx.gbl>
Message-ID: <4F2659AC.3060100@compuscan.co.za>

On 2012/01/30 07:20 AM, Surya K wrote:
> I want to run code until a "enter" is pressed. Well, it shouldn't wait 
> for the user to enter "enter"
>
> This is my code:
>
> import msvcrt
>
> chr = 0
> while chr != 'q':
>      print "my code",
>      if msvcrt.kbhit():
>            chr = msvcrt.getch()
>
> This isn't working the way I wanted. When ever I press enter, the loop 
> is starting in a new line and continuing.
>
> I even added "break" statement in "if" block but it isn't working
> Can you tell me how to do that?
>
> I am on windows. So, as msvcrt is for windows, I wonder if there is 
> any module that works for both,
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
There isn't a platform independent module for capturing keystrokes 
unfortunately.  You can take a look at this StackOverflow answer though 
which could help you out 
http://stackoverflow.com/questions/5044073/python-cross-platform-listening-for-keypresses 

-- 

Christian Witts
Python Developer
//
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120130/2ecca6f0/attachment.html>

From steve at pearwood.info  Mon Jan 30 10:55:43 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 30 Jan 2012 20:55:43 +1100
Subject: [Tutor] loop until a keypress
In-Reply-To: <SNT130-W397E068F9E47ABD82EEA34A48D0@phx.gbl>
References: <SNT130-W397E068F9E47ABD82EEA34A48D0@phx.gbl>
Message-ID: <4F26691F.5060209@pearwood.info>

Surya K wrote:
> I am on windows. So, as msvcrt is for windows, I wonder if there
> is any module that works for both,

http://code.activestate.com/recipes/577977


-- 
Steven

From geonyoro at gmail.com  Mon Jan 30 15:32:26 2012
From: geonyoro at gmail.com (George Nyoro)
Date: Mon, 30 Jan 2012 17:32:26 +0300
Subject: [Tutor] Sort
Message-ID: <CAM71YVESuHB+v6oAK7vZ_DUU60px1geHeNoZYjV_noZN1PoK4A@mail.gmail.com>

Hey all, again:
Thanks for the delete thing. Helped with that problem a lot. Especially the
getattr thing came in handy.

Question 1:
How do you guys indent and put in the triple greater than signs and all
that when sending mail? Manually? Coz the last mail I sent was using the
gmail indent thing and it doesnt seem to have worked. Anyway:

Question 2:
I have this script that downloaded a lot of files from one server into one
local directory and the files are named in a particular order and I want
them to be opened in this very same order so that I can copy the contents
of each to one main file and then convert to pdf. However, the naming
schema is like this (Roman numerals in parts) and python doesn't seem to be
able to sort it properly.
1.I.1; 1.I.2; ....; 1.I.20;
1.II.1.1;1.II.1.2
1.II.2;...1.II.10; 2.I.3;
Because of the roman numerals that are always in the second part fo the
filename, it could sort based on how I wanted.

I listed all the files in the said directory:
files=os.listdir(location)

I tried using a sort algorithm that goes through the list starting from
index 0 and then compares each index with the next one and if they are not
arranged as they should be, the two are switched and then it starts again.
The thing is, it is so slow! It hardly goes past index three in the list
and there are so many files. *about fifty*.

Could anyone help me with the python impelentation of such an algorith and
how it should sort. Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120130/d1f7b8cf/attachment.html>

From arunkumar413 at gmail.com  Mon Jan 30 16:13:32 2012
From: arunkumar413 at gmail.com (Arun Kumar)
Date: Mon, 30 Jan 2012 20:43:32 +0530
Subject: [Tutor] Tutor Digest, Vol 95, Issue 80
In-Reply-To: <mailman.28561.1327909998.27777.tutor@python.org>
References: <mailman.28561.1327909998.27777.tutor@python.org>
Message-ID: <CAN+mmKa5i9=r_qixmbXNc-5PrAA=sJ7VEPF5Kr8wJ7dgx36AZQ@mail.gmail.com>

Dear Ganesh,

Glade is just an user interface builder. It is just a Rapid Application
Development (RAD) tool that simplifies designing the user interface. But
you still need to program what the interface does. This is done by PyGTK, a
toolkit, or a collection of libraries, which developers can use to develop
GUI applications for Linux, OSX, Windows, and any other platform on which
GTK+ is available. I think this tutorial may be helpful to you.

http://www.micahcarrick.com/gtk-glade-tutorial-part-1.html
http://www.pygtk.org/pygtk2tutorial/index.html

On Mon, Jan 30, 2012 at 1:23 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. Re: Deleting an object (Peter Otten)
>   2. Re: Deleting an object (Alan Gauld)
>   3. Re: Socket Programming (Navneet)
>   4. Re: Why do you have to close files? (amt)
>   5. loop until a keypress (Surya K)
>   6. Help Glade Tutorial. (Ganesh Kumar)
>   7. Re: Help Glade Tutorial. (Chris Fuller)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Sun, 29 Jan 2012 17:34:12 +0100
> From: Peter Otten <__peter__ at web.de>
> To: tutor at python.org
> Subject: Re: [Tutor] Deleting an object
> Message-ID: <jg3se3$seo$1 at dough.gmane.org>
> Content-Type: text/plain; charset="ISO-8859-1"
>
> George Nyoro wrote:
>
> >        Last time I tried to post a question regarding this, I was asked
> to
> > clarify. Okay so here it is. There is a class called Table and objects
> are
> > just tables, you know, matrices, holding different types of data. Thing
> > is, I want to provide a method where one can delete the object and then
> if
> > the user tries using a variable to access a certain method or attributes,
> > he gets an error. Let me give an example;
> >
> > class Table:
> >     def delete_this(self):
> >         #code to delete this object or assign it null or None
> >         pass
> >
> >     def do_something(self):
> >         pass
>
> > x=Table()
> > x.delete_this()
> >
> > #at this point, I want such that if I try to use x I get some sort of
> > #error
> > e.g.
> >
> > x.do_something()
> >
> > #Error: x is definitely not an object anymore
> >
> >
> >  All clear?
>
>
> >>> class Parrot:
> ...     def hello(self):
> ...             print("Hello")
> ...     def delete_this(self):
> ...             self.__class__ = DeadParrot
> ...
> >>> class DeadParrot:
> ...     def __getattr__(self, name):
> ...             raise Exception("This parrot is no more")
> ...
> >>> p = Parrot()
> >>> p.hello()
> Hello
> >>> p.delete_this()
> >>> p.hello()
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
>  File "<stdin>", line 3, in __getattr__
> Exception: This parrot is no more
>
> But I don't think it's a good idea...
>
>
>
> ------------------------------
>
> Message: 2
> Date: Sun, 29 Jan 2012 18:05:59 +0000
> From: Alan Gauld <alan.gauld at btinternet.com>
> To: tutor at python.org
> Subject: Re: [Tutor] Deleting an object
> Message-ID: <jg41q7$6lq$1 at dough.gmane.org>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> On 29/01/12 15:14, George Nyoro wrote:
>
> > data. Thing is, I want to provide a method where one can delete the
> > object and then if the user tries using a variable to access a certain
> > method or attributes, he gets an error. Let me give an example;
>
> I assume you know about the built in del() function that deletes
> objects? It works on any kind of object.
>
> If you need it to do sometjing fancy(like releasing resources say) you
> can define your own __del__() method that gets called by Python when the
> object is deleted - but you rarely need to do that in Python.
>
> > class Table:
> >    def delete_this(self):
> >    def do_something(self):
>
> > x=Table()
> > x.delete_this()
> > #at this point, I want such that if I try to use x I get some sort of
> > error e.g.
>
> x = Table()
> del(x)
>
> now referencing x or any attribute or method will give a name error.
> Here is an example using an int, but any kind of object works:
>
>  >>> x = 42
>  >>> x
> 42
>  >>> del(x)
>  >>> x
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'x' is not defined
>  >>>
>
> If thats not what you want you need to come vback and explain what is
> different about your scenario.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
> ------------------------------
>
> Message: 3
> Date: Sun, 29 Jan 2012 21:01:47 +0100
> From: Navneet <rocklearnpython at gmail.com>
> To: tutor at python.org
> Subject: Re: [Tutor] Socket Programming
> Message-ID: <4F25A5AB.5070903 at gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> On 1/27/2012 10:13 PM, Steven D'Aprano wrote:
> > Navneet wrote:
> >
> >> One more thing I want to add here is, I am trying to create the GUI
> >> based chat server.(Attached the programs.)
> >
> >
> > Please do not send large chunks of code like this, unless asked.
> > Instead, you should try to produce a minimal example that demonstrates
> > the problem. It should be:
> >
> > * short (avoid code which has nothing to do with the problem)
> >
> > * self-contained (other people must be able to run it)
> >
> > * correct (it must actually fail in the way you say it fails)
> >
> > See here for more: http://sscce.org/
> >
> >
> > In cutting your code down to a minimal example, 9 times out of 10 you
> > will solve your problem yourself, and learn something in the process.
> >
> >
> >> bash-3.1$ python Client1.py
> >> Enter the server address:...9009
> >> Traceback (most recent call last):
> >>   File "Client1.py", line 53, in <module>
> >>     c = ClientChat(serverport)
> >>   File "Client1.py", line 24, in __init__
> >>     gui.callGui()
> >>   File "a:\FedEx\Exp\ClientGui.py", line 37, in callGui
> >>     sendbutton =Button(f2, width = 5, height = 2, text = "Send",
> >> command = C.ClientChat.senddata())
> >> TypeError: unbound method senddata() must be called with ClientChat
> >> instance as first argument (got nothing instead)
> >
> >
> > This one is easy. You need to initialize a ClientChat instance first.
> > This may be as simple as:
> >
> > command = C.ClientChat().senddata
> >
> > although I'm not sure if ClientChat requires any arguments.
> >
> > Note that you call the ClientChat class, to create an instance, but
> > you DON'T call the senddata method, since you want to pass the method
> > itself as a callback function. The button will call it for you, when
> > needed.
> >
> >
> >
> Thanks for the clarification and telling me about SSCCE :)
>
> But just a simple thing,,, Can I call a method of another module while
> creating a GUI.
>
> For example
>  C = Tk()
> .....(Some more lines)
> self.sendbutton =Button(self.f2, width = 5, height = 2, text = "Send",
> command = <ANOTHER MODULE>.<METHOD OF THAT MODULE>)
>         self.sendbutton.pack(side = LEFT, padx = 10, pady = 10)
> .....(Some more lines)
> C.mainloop()
>
>
> Because I am getting stuck in a loop. The client is keep on connecting
> to server without creating a GUI.
>
>
>
>
>
>
>
>
>
>
>
>
>
> ------------------------------
>
> Message: 4
> Date: Mon, 30 Jan 2012 00:28:21 +0200
> From: amt <0101amt at gmail.com>
> To: tutor at python.org
> Subject: Re: [Tutor] Why do you have to close files?
> Message-ID:
>        <CAEQEn016afJDN+2F_+R-rm2d4MbWGXvN9_ed-AQoNmT=F2VKiQ at mail.gmail.com
> >
> Content-Type: text/plain; charset=ISO-8859-1
>
> All the replies were very helpful! Thank you very much for helping me out!
>
>
> ------------------------------
>
> Message: 5
> Date: Mon, 30 Jan 2012 10:50:51 +0530
> From: Surya K <suryak at live.com>
> To: Python Tutor <tutor at python.org>
> Subject: [Tutor] loop until a keypress
> Message-ID: <SNT130-W397E068F9E47ABD82EEA34A48D0 at phx.gbl>
> Content-Type: text/plain; charset="iso-8859-1"
>
>
> I want to run code until a "enter" is pressed. Well, it shouldn't wait for
> the user to enter "enter"
> This is my code:
> import msvcrtchr = 0while chr != 'q':     print "my code",     if
> msvcrt.kbhit():           chr = msvcrt.getch()
> This isn't working the way I wanted. When ever I press enter, the loop is
> starting in a new line and continuing.
> I even added "break" statement in "if" block but it isn't workingCan you
> tell me how to do that?
> I am on windows. So, as msvcrt is for windows, I wonder if there is any
> module that works for both,
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: <
> http://mail.python.org/pipermail/tutor/attachments/20120130/a5996b2a/attachment-0001.html
> >
>
> ------------------------------
>
> Message: 6
> Date: Mon, 30 Jan 2012 11:55:12 +0530
> From: Ganesh Kumar <bugcy013 at gmail.com>
> To: tutor at python.org
> Subject: [Tutor] Help Glade Tutorial.
> Message-ID:
>        <CAJzooYc-OaR6JOz9WRJBtv0W6t3L2ZL0dZV+GUyD-yUP9xe-JQ at mail.gmail.com
> >
> Content-Type: text/plain; charset="utf-8"
>
> Hi Guys,
>
> I am searching for a Glade tutorial, on how to create simple projects Glade
> with python
>
> 1) design a simple interface in glade
> 2) use the glade interface to write some really simple application with
> python.
>
> I search in goggled i didn't get good tutorials, guide me guys How to start
> with Glade.
>
> -Ganesh
>
> Did I learn something today? If not, I wasted it.
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: <
> http://mail.python.org/pipermail/tutor/attachments/20120130/fec2e0a2/attachment-0001.html
> >
>
> ------------------------------
>
> Message: 7
> Date: Mon, 30 Jan 2012 00:51:58 -0600
> From: Chris Fuller <cfuller084 at thinkingplanet.net>
> To: tutor at python.org
> Subject: Re: [Tutor] Help Glade Tutorial.
> Message-ID: <201201300051.58828.cfuller084 at thinkingplanet.net>
> Content-Type: Text/Plain;  charset="utf-8"
>
>
> Which ones did you look at, and why did you not like them?  Keep in mind
> that
> Glade is an interface builder, and hasn't got anything much to do with the
> target language, other than requiring there be a libglade library to read
> the
> XML files.
>
> I actually got started with some articles in Linux Journal, which don't
> appear
> high on the google search unless you include those terms.  Search for
> "glade
> tutorial" or "glade linux journal".  Leave Python or pyGTK out of your
> search
> for now.
>
> You might need a little help with using the XML files glade produces, but
> that's covered in the pyGTK documentation.  It's also in the Linux Journal
> articles.  You can google "pygtk glade" if you need more.
>
> Cheers
>
> On Monday 30 January 2012, Ganesh Kumar wrote:
> > Hi Guys,
> >
> > I am searching for a Glade tutorial, on how to create simple projects
> Glade
> > with python
> >
> > 1) design a simple interface in glade
> > 2) use the glade interface to write some really simple application with
> > python.
> >
> > I search in goggled i didn't get good tutorials, guide me guys How to
> start
> > with Glade.
> >
> > -Ganesh
> >
> > Did I learn something today? If not, I wasted it.
>
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 95, Issue 80
> *************************************
>



-- 
Thanks & Regards,

Arun Kumar
http://clicknscroll.blogspot.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120130/007e3ea2/attachment-0001.html>

From steve at pearwood.info  Mon Jan 30 16:17:00 2012
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 31 Jan 2012 02:17:00 +1100
Subject: [Tutor] Sort
In-Reply-To: <CAM71YVESuHB+v6oAK7vZ_DUU60px1geHeNoZYjV_noZN1PoK4A@mail.gmail.com>
References: <CAM71YVESuHB+v6oAK7vZ_DUU60px1geHeNoZYjV_noZN1PoK4A@mail.gmail.com>
Message-ID: <4F26B46C.6070704@pearwood.info>

George Nyoro wrote:
> Hey all, again:
> Thanks for the delete thing. Helped with that problem a lot. Especially the
> getattr thing came in handy.
> 
> Question 1:
> How do you guys indent and put in the triple greater than signs and all
> that when sending mail? Manually? Coz the last mail I sent was using the
> gmail indent thing and it doesnt seem to have worked. Anyway:


Copy text including >>> signs, and any other characters you want.
Paste into your email client. The characters should appear exactly as you 
copied and pasted them.

If your email client (gmail) takes it upon itself to mangle your text, then 
use a better email client that doesn't suck. (Any software which thinks it 
knows what you want better than you do should be taken out and slapped with a 
wet fish.)


> Question 2:
> I have this script that downloaded a lot of files from one server into one
> local directory and the files are named in a particular order and I want
> them to be opened in this very same order so that I can copy the contents
> of each to one main file and then convert to pdf. However, the naming
> schema is like this (Roman numerals in parts) and python doesn't seem to be
> able to sort it properly.
> 1.I.1; 1.I.2; ....; 1.I.20;
> 1.II.1.1;1.II.1.2
> 1.II.2;...1.II.10; 2.I.3;

I don't understand this. Is each line ONE file name, or are there many file 
names per line? Are the semi-colons part of the file names?

I'm going to *guess* that each file name has THREE sections only, with no 
semi-colons, and look like these 3 examples:

1.I.1
1.III.20
5.IX.7

etc. Am I close?


> Because of the roman numerals that are always in the second part fo the
> filename, it could sort based on how I wanted.
> 
> I listed all the files in the said directory:
> files=os.listdir(location)
> 
> I tried using a sort algorithm that goes through the list starting from
> index 0 and then compares each index with the next one and if they are not
> arranged as they should be, the two are switched and then it starts again.
> The thing is, it is so slow! It hardly goes past index three in the list
> and there are so many files. *about fifty*.

Congratulations! You appear to have re-invented one of the world's slowest 
sorting functions, bubblesort. <wink> Look it up on Wikipedia.

Only probably with a bug in it, because even bubblesort shouldn't get stuck 
after only three files.

Except as a learning exercise, or to prove you can, never try to program your 
own sort in Python. That's like buying a car, and then putting it on the back 
of your push-bike and trying to cycle home with it. Uphill. In the snow. With 
a flat tire.

Instead, you should use Python's built-in sort function, which if you use it 
properly is faster than anything you can write (unless you are Tim Peters, who 
invented it in the first place).

Normally, you would just do something like this:

files = os.listdir(location)
files.sort()  # sort the list in-place, without making a copy


or perhaps this:

files = sorted(os.listdir(location))  # make a copy and sort


but in this case you have special requirements, thanks to the naming 
convention for your files. In this case, you don't want the ordinary sort 
order for strings, you need a special sort order based on Roman numerals.

The best way to sort these is with a technique called:

Decorate, Sort, Undecorate

also known as DSU, which sorted() supports using a key function. It sounds 
harder than it is. In this case, you need to decorate each file name (which is 
hard to sort!) with something that is easier to sort. In this case, the 
filenames look like:

number DOT roman number DOT number

all as one string, so the obvious way to sort them is to convert to three 
numbers. The first and last numbers are easy, you just use the int() function, 
the roman number is a bit trickier because Python doesn't have a built-in 
converter.

So here is my converter, and a decorate function that uses it:

def from_roman(s):
     # Convert Roman numerals into an integer.
     table = {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5, 'VI': 6,
              'VII': 7, 'VIII': 8, 'IX': 9, 'X': 10}  # Is this enough?
     return table[s.upper()]


def decorate(filename):
     a, b, c = filename.split(".")  # Split into three pieces, at the dots.
     a = int(a)  # Convert the first and last into integers.
     c = int(c)
     b = from_roman(b)  # and the middle using roman numerals
     return (a, b, c)



And finally you can do the sorting like so:


files = sorted(os.listdir(location), key=decorate)


Note that Python will do the undecorate part automatically.

Warning: I have not tested any of this. It should work, but it's not 
unpossible for me to have make a misteak.



-- 
Steven


From williamjstewart at rogers.com  Mon Jan 30 20:02:59 2012
From: williamjstewart at rogers.com (William Stewart)
Date: Mon, 30 Jan 2012 11:02:59 -0800 (PST)
Subject: [Tutor] New user Knows nothing about python I Need HELP
In-Reply-To: <mailman.0.1327949950.23425.tutor@python.org>
Message-ID: <1327950179.93704.YahooMailClassic@web88616.mail.bf1.yahoo.com>




hello
I am trying to make a math functions program which includes
ADDITION: 2+2=4
SUBTRACTION: 4-2=2
MULTIPLICATION: 4*2=8
DIVISION: 4/2=2 
EXPONENT: 2**3=8
REMAINDER: 5%2=1

I have no Idea how to start this task I have never used ANY programming programs before And I dont Know the language either
The online help files from python Did not help a bit
please help
thank you
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120130/d350ce8d/attachment.html>

From malaclypse2 at gmail.com  Mon Jan 30 20:21:40 2012
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Mon, 30 Jan 2012 14:21:40 -0500
Subject: [Tutor] New user Knows nothing about python I Need HELP
In-Reply-To: <1327950179.93704.YahooMailClassic@web88616.mail.bf1.yahoo.com>
References: <mailman.0.1327949950.23425.tutor@python.org>
	<1327950179.93704.YahooMailClassic@web88616.mail.bf1.yahoo.com>
Message-ID: <CADwdpyZkD9Vh9zyJ4PF1h+Lz=SGBLfsFheNP0hQ4ovoe0y0pmA@mail.gmail.com>

On Mon, Jan 30, 2012 at 2:02 PM, William Stewart
<williamjstewart at rogers.com> wrote:
> I have no Idea how to start this task I have never used ANY programming programs before And I dont Know the language either
> The online help files from python Did not help a bit


Here's a few resources that might get you started.

First, if you haven't seen it, I found the official python tutorial to
be a great place to start: http://docs.python.org/tutorial/  That may
assume more familiarity with programming in general than you are
comfortable with, though.

In that case, you might be interested in a whole bunch of resources
designed to teach python to people who haven't done any programming at
all: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

Once you're a bit more comfortable, there are a ton more documentation
aimed at learning python for people who are already somewhat familiar
with other programming languages:
http://wiki.python.org/moin/BeginnersGuide/Programmers

Hope that helps some,
Jerry

From joel.goldstick at gmail.com  Mon Jan 30 21:00:15 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 30 Jan 2012 15:00:15 -0500
Subject: [Tutor] New user Knows nothing about python I Need HELP
In-Reply-To: <CADwdpyZkD9Vh9zyJ4PF1h+Lz=SGBLfsFheNP0hQ4ovoe0y0pmA@mail.gmail.com>
References: <mailman.0.1327949950.23425.tutor@python.org>
	<1327950179.93704.YahooMailClassic@web88616.mail.bf1.yahoo.com>
	<CADwdpyZkD9Vh9zyJ4PF1h+Lz=SGBLfsFheNP0hQ4ovoe0y0pmA@mail.gmail.com>
Message-ID: <CAPM-O+zKO0m5UZWzNTnq5NF+8ujR8VMBR3Jnm6-rbviX5EzuXA@mail.gmail.com>

On Mon, Jan 30, 2012 at 2:21 PM, Jerry Hill <malaclypse2 at gmail.com> wrote:
> On Mon, Jan 30, 2012 at 2:02 PM, William Stewart
> <williamjstewart at rogers.com> wrote:
>> I have no Idea how to start this task I have never used ANY programming programs before And I dont Know the language either
>> The online help files from python Did not help a bit
>
>
> Here's a few resources that might get you started.
>
> First, if you haven't seen it, I found the official python tutorial to
> be a great place to start: http://docs.python.org/tutorial/ ?That may
> assume more familiarity with programming in general than you are
> comfortable with, though.
>
> In that case, you might be interested in a whole bunch of resources
> designed to teach python to people who haven't done any programming at
> all: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
>
> Once you're a bit more comfortable, there are a ton more documentation
> aimed at learning python for people who are already somewhat familiar
> with other programming languages:
> http://wiki.python.org/moin/BeginnersGuide/Programmers
>
> Hope that helps some,
> Jerry
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

>From the nature of your question, I am guessing you are taking a class
and this is homework?  If so, can you tell us what you have learned so
far or what topics have been covered in your class?

If this just for general interest.  the resources above are a good start


-- 
Joel Goldstick

From joel.goldstick at gmail.com  Mon Jan 30 23:59:59 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 30 Jan 2012 17:59:59 -0500
Subject: [Tutor] New user Knows nothing about python I Need HELP
In-Reply-To: <1327963287.42324.YahooMailClassic@web88618.mail.bf1.yahoo.com>
References: <CAPM-O+zKO0m5UZWzNTnq5NF+8ujR8VMBR3Jnm6-rbviX5EzuXA@mail.gmail.com>
	<1327963287.42324.YahooMailClassic@web88618.mail.bf1.yahoo.com>
Message-ID: <CAPM-O+zkEAYDChN1FwjKuBPPJs1K=s3iRXH5WxKhNsJxVqj5Kw@mail.gmail.com>

On Mon, Jan 30, 2012 at 5:41 PM, William Stewart <williamjstewart at rogers.com
> wrote:

> thanks I havent learned anything about prgramming its a computer sicence
> class, I will try  the links
> thanks again
>
> --- On *Mon, 1/30/12, Joel Goldstick <joel.goldstick at gmail.com>* wrote:
>
>
> From: Joel Goldstick <joel.goldstick at gmail.com>
> Subject: Re: [Tutor] New user Knows nothing about python I Need HELP
> To: "Jerry Hill" <malaclypse2 at gmail.com>
> Cc: "William Stewart" <williamjstewart at rogers.com>, tutor at python.org
> Date: Monday, January 30, 2012, 3:00 PM
>
>
> On Mon, Jan 30, 2012 at 2:21 PM, Jerry Hill <malaclypse2 at gmail.com<http://ca.mc886.mail.yahoo.com/mc/compose?to=malaclypse2 at gmail.com>>
> wrote:
> > On Mon, Jan 30, 2012 at 2:02 PM, William Stewart
> > <williamjstewart at rogers.com<http://ca.mc886.mail.yahoo.com/mc/compose?to=williamjstewart at rogers.com>>
> wrote:
> >> I have no Idea how to start this task I have never used ANY programming
> programs before And I dont Know the language either
> >> The online help files from python Did not help a bit
> >
> >
> > Here's a few resources that might get you started.
> >
> > First, if you haven't seen it, I found the official python tutorial to
> > be a great place to start: http://docs.python.org/tutorial/  That may
> > assume more familiarity with programming in general than you are
> > comfortable with, though.
> >
> > In that case, you might be interested in a whole bunch of resources
> > designed to teach python to people who haven't done any programming at
> > all: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
> >
> > Once you're a bit more comfortable, there are a ton more documentation
> > aimed at learning python for people who are already somewhat familiar
> > with other programming languages:
> > http://wiki.python.org/moin/BeginnersGuide/Programmers
> >
> > Hope that helps some,
> > Jerry
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org<http://ca.mc886.mail.yahoo.com/mc/compose?to=Tutor at python.org>
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
>
> From the nature of your question, I am guessing you are taking a class
> and this is homework?  If so, can you tell us what you have learned so
> far or what topics have been covered in your class?
>
> If this just for general interest.  the resources above are a good start
>
>
> --
> Joel Goldstick
>
> William,

First, reply to all so that the group sees your response.  Second, aside
from the reading, find a classmate or two who are feeling like you are.

python has an interactive shell that you get to by just typing python from
a terminal prompt.  When you go through a tutorial or examples, try things
out in the shell.  You'll learn a lot that way


-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120130/ef7d4ab0/attachment-0001.html>

From mjolewis at gmail.com  Tue Jan 31 05:50:42 2012
From: mjolewis at gmail.com (Michael Lewis)
Date: Mon, 30 Jan 2012 20:50:42 -0800
Subject: [Tutor] ASCII Conversion
Message-ID: <CAE5MWfXZ9Jkm8-ATYxTenNnfjc4SUx4LomwW+gCrTOX6oOHaPA@mail.gmail.com>

I am trying to do a simple test but am not sure how to get around ASCII
conversion of characters. I want to pass in y have the function test to see
if y is an integer and print out a value if that integer satisfies the if
statement. However, if I pass in a string, it's converted to ASCII and will
still satisfy the if statement and print out value. How do I ensure that a
string is caught as a ValueError instead of being converted?

def TestY(y):
    try:
        y = int(y)
    except ValueError:
        pass
    if y < -1 or y > 1:
        value = 82
        print value
    else:
        pass

-- 
Michael J. Lewis

mjolewis at gmail.com
415.815.7257
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120130/2578531d/attachment.html>

From davekidd at gmail.com  Tue Jan 31 06:25:54 2012
From: davekidd at gmail.com (David Kidd)
Date: Tue, 31 Jan 2012 16:25:54 +1100
Subject: [Tutor] ASCII Conversion
In-Reply-To: <CAE5MWfXZ9Jkm8-ATYxTenNnfjc4SUx4LomwW+gCrTOX6oOHaPA@mail.gmail.com>
References: <CAE5MWfXZ9Jkm8-ATYxTenNnfjc4SUx4LomwW+gCrTOX6oOHaPA@mail.gmail.com>
Message-ID: <CA+Z-2WgapejUfazL8pGK5OEqtL20fG6eHiTsaETNngzTHmLVHQ@mail.gmail.com>

On Tue, Jan 31, 2012 at 15:50, Michael Lewis <mjolewis at gmail.com> wrote:
> ... However, if I pass in a string, it's converted to ASCII and will
> still satisfy the if statement and print out value. How do I ensure that a
> string is caught as a ValueError instead of being converted?

It depends on what you want to do if you catch a string. If you just
want to end the function, you could just try returning on the
exception, rather than passing. This will stop the string from being
processed any further.

From cwitts at compuscan.co.za  Tue Jan 31 06:33:35 2012
From: cwitts at compuscan.co.za (Christian Witts)
Date: Tue, 31 Jan 2012 07:33:35 +0200
Subject: [Tutor] ASCII Conversion
In-Reply-To: <CAE5MWfXZ9Jkm8-ATYxTenNnfjc4SUx4LomwW+gCrTOX6oOHaPA@mail.gmail.com>
References: <CAE5MWfXZ9Jkm8-ATYxTenNnfjc4SUx4LomwW+gCrTOX6oOHaPA@mail.gmail.com>
Message-ID: <4F277D2F.6020504@compuscan.co.za>

On 2012/01/31 06:50 AM, Michael Lewis wrote:
> I am trying to do a simple test but am not sure how to get around 
> ASCII conversion of characters. I want to pass in y have the function 
> test to see if y is an integer and print out a value if that integer 
> satisfies the if statement. However, if I pass in a string, it's 
> converted to ASCII and will still satisfy the if statement and print 
> out value. How do I ensure that a string is caught as a ValueError 
> instead of being converted?
>
> def TestY(y):
>     try:
>         y = int(y)
>     except ValueError:
>         pass
>     if y < -1 or y > 1:
>         value = 82
>         print value
>     else:
>         pass
>
> -- 
> Michael J. Lewis
> mjolewis at gmail.com <mailto:mjolewis at gmail.com>
> 415.815.7257
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
If you just want to test if `y` is an integer you can do so with 
`type(y) == int`, and to get the ASCII value of a character you can use 
`ord` like `ord('a') == 97`. And how to avoid your ValueError with a bad 
conversion, do your type checking before hand.

Hope that helps.
-- 

Christian Witts
Python Developer
//
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120131/0be17207/attachment.html>

From breamoreboy at yahoo.co.uk  Tue Jan 31 07:16:43 2012
From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi)
Date: Tue, 31 Jan 2012 06:16:43 +0000
Subject: [Tutor] ASCII Conversion
In-Reply-To: <4F277D2F.6020504@compuscan.co.za>
References: <CAE5MWfXZ9Jkm8-ATYxTenNnfjc4SUx4LomwW+gCrTOX6oOHaPA@mail.gmail.com>
	<4F277D2F.6020504@compuscan.co.za>
Message-ID: <jg80v9$3qf$1@dough.gmane.org>

On 31/01/2012 05:33, Christian Witts wrote:
> On 2012/01/31 06:50 AM, Michael Lewis wrote:
>> I am trying to do a simple test but am not sure how to get around
>> ASCII conversion of characters. I want to pass in y have the function
>> test to see if y is an integer and print out a value if that integer
>> satisfies the if statement. However, if I pass in a string, it's
>> converted to ASCII and will still satisfy the if statement and print
>> out value. How do I ensure that a string is caught as a ValueError
>> instead of being converted?
>>
>> def TestY(y):
>>     try:
>>         y = int(y)
>>     except ValueError:
>>         pass
>>     if y < -1 or y > 1:
>>         value = 82
>>         print value
>>     else:
>>         pass
>>
>> --
>> Michael J. Lewis
>> mjolewis at gmail.com <mailto:mjolewis at gmail.com>
>> 415.815.7257
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
> If you just want to test if `y` is an integer you can do so with
> `type(y) == int`, and to get the ASCII value of a character you can use
> `ord` like `ord('a') == 97`. And how to avoid your ValueError with a bad
> conversion, do your type checking before hand.
>
> Hope that helps.
> --
>
> Christian Witts
> Python Developer
> //
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

The test of y would not normally be written as it is, comparisons can be 
chained see http://docs.python.org/reference/expressions.html#not-in.
Also Python tends to use EAFP rather than LBYL see 
http://docs.python.org/glossary.html.

-- 
Cheers.

Mark Lawrence.


From __peter__ at web.de  Tue Jan 31 08:40:38 2012
From: __peter__ at web.de (Peter Otten)
Date: Tue, 31 Jan 2012 08:40:38 +0100
Subject: [Tutor] ASCII Conversion
References: <CAE5MWfXZ9Jkm8-ATYxTenNnfjc4SUx4LomwW+gCrTOX6oOHaPA@mail.gmail.com>
Message-ID: <jg85tn$25k$1@dough.gmane.org>

Michael Lewis wrote:

> I am trying to do a simple test but am not sure how to get around ASCII
> conversion of characters. I want to pass in y have the function test to
> see if y is an integer and print out a value if that integer satisfies the
> if statement. However, if I pass in a string, it's converted to ASCII and
> will still satisfy the if statement and print out value. How do I ensure
> that a string is caught as a ValueError instead of being converted?
> 
> def TestY(y):
>     try:
>         y = int(y)
>     except ValueError:
>         pass
>     if y < -1 or y > 1:
>         value = 82
>         print value
>     else:
>         pass

You have to remember somehow whether you have an integer or a string. A 
straightforward way is

def test(y):
    try:
        y = int(y)
        isint = True 
    except ValueError:
        isint = False
    if isint and y < -1 or y > 1:
        print 82


However, Python's try..except statement features an else suite that is only 
invoked when no exception is raised. So the idiomatic way is to drop the 
helper variable and change the control flow instead:

def test(y):
    try:
        y = int(y)
    except ValueError:
        pass
    else:
        if y < -1 or y > 1:
            print 82


From __peter__ at web.de  Tue Jan 31 08:53:14 2012
From: __peter__ at web.de (Peter Otten)
Date: Tue, 31 Jan 2012 08:53:14 +0100
Subject: [Tutor] ASCII Conversion
References: <CAE5MWfXZ9Jkm8-ATYxTenNnfjc4SUx4LomwW+gCrTOX6oOHaPA@mail.gmail.com>
	<jg85tn$25k$1@dough.gmane.org>
Message-ID: <jg86la$5bj$1@dough.gmane.org>

Peter Otten wrote:

> if isint and y < -1 or y > 1:
 
Sorry, I forgot the parentheses.


From russel at russel.org.uk  Tue Jan 31 10:06:09 2012
From: russel at russel.org.uk (Russel Winder)
Date: Tue, 31 Jan 2012 09:06:09 +0000
Subject: [Tutor] ASCII Conversion
In-Reply-To: <4F277D2F.6020504@compuscan.co.za>
References: <CAE5MWfXZ9Jkm8-ATYxTenNnfjc4SUx4LomwW+gCrTOX6oOHaPA@mail.gmail.com>
	<4F277D2F.6020504@compuscan.co.za>
Message-ID: <1328000769.30156.18.camel@anglides.russel.org.uk>

On Tue, 2012-01-31 at 07:33 +0200, Christian Witts wrote:
> [...]o with 
> `type(y) == int`, and to get the ASCII value of a character you can use 
> `ord` like `ord('a') == 97`. And how to avoid your ValueError with a bad 
> conversion, do your type checking before hand.

isinstance ( y , int ) 

preferred?

Violates EAFP obviously but...

-- 
Russel.
=============================================================================
Dr Russel Winder      t: +44 20 7585 2200   voip: sip:russel.winder at ekiga.net
41 Buckmaster Road    m: +44 7770 465 077   xmpp: russel at russel.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part
URL: <http://mail.python.org/pipermail/tutor/attachments/20120131/e3256acb/attachment-0001.pgp>

From joel.goldstick at gmail.com  Tue Jan 31 21:28:08 2012
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 31 Jan 2012 15:28:08 -0500
Subject: [Tutor] ASCII Conversion
In-Reply-To: <1328000769.30156.18.camel@anglides.russel.org.uk>
References: <CAE5MWfXZ9Jkm8-ATYxTenNnfjc4SUx4LomwW+gCrTOX6oOHaPA@mail.gmail.com>
	<4F277D2F.6020504@compuscan.co.za>
	<1328000769.30156.18.camel@anglides.russel.org.uk>
Message-ID: <CAPM-O+wmSMf6HwU2Sz16fcZqHWC_O9cSVP7g5iMEGFbRNSmQWw@mail.gmail.com>

On Tue, Jan 31, 2012 at 4:06 AM, Russel Winder <russel at russel.org.uk> wrote:
> On Tue, 2012-01-31 at 07:33 +0200, Christian Witts wrote:
>> [...]o with
>> `type(y) == int`, and to get the ASCII value of a character you can use
>> `ord` like `ord('a') == 97`. And how to avoid your ValueError with a bad
>> conversion, do your type checking before hand.
>
> isinstance ( y , int )
>
> preferred?
>
> Violates EAFP obviously but...
>
> --
> Russel.
> =============================================================================
> Dr Russel Winder ? ? ?t: +44 20 7585 2200 ? voip: sip:russel.winder at ekiga.net
> 41 Buckmaster Road ? ?m: +44 7770 465 077 ? xmpp: russel at russel.org.uk
> London SW11 1EN, UK ? w: www.russel.org.uk ?skype: russel_winder
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


I took a slightly different approach as shown:

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.
>>> def test(y):
...   try:
...     if abs(y) > 1:
...       print 83
...   except ValueError:
...     pass
...
>>> test(.5)
>>> test(5)
83
>>> test('bob')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in test
TypeError: bad operand type for abs(): 'str'
>>> int('bob')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'bob'
>>>

First, I like abs(y) > 1 rather than the double test which is
confusing for me to read.
This fails if y isn't a number, but it fails with ValueError instead
of TypeError.
Since I was just playing around, I have printed the complete session.
To make my code play right, I would substitue the ValueError where I
have TypeError and I think I have what you wanted.

Oh, I used 83 instead of 82.. No idea why I did that

-- 
Joel Goldstick