Re: [Tutor] thesaurus

2009-07-10 Thread Dave Angel

Alan Gauld wrote:


"Angus Rodgers"  wrote

parsing these two sentences:

Time flies like an arrow.
Fruit flies like a banana.


Or the translation program that translated the expression

Out of sight, out of mind

from English to Russian and back with the result:

Invisible, lunatic

Alan G.





Or the expression:
"The spirit is willing, but the flesh is weak"
to:
"The wine is good, but the meat is rotten"

DaveA

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] thesaurus

2009-07-10 Thread Kent Johnson
On Fri, Jul 10, 2009 at 7:08 AM, Dave Angel wrote:
> Alan Gauld wrote:

>> Or the translation program that translated the expression
>>
>> Out of sight, out of mind
>>
>> from English to Russian and back with the result:
>>
>> Invisible, lunatic

> Or the expression:
> "The spirit is willing, but the flesh is weak"
> to:
> "The wine is good, but the meat is rotten"

These are fun but, according to snopes.com, they are probably urban
legend rather than fact:
http://www.snopes.com/language/misxlate/machine.asp

FWIW translate.google.com correctly translates both of the above from
English to Russian and back. I wonder if they have optimized for those
phrases?

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] thesaurus

2009-07-10 Thread Dave Angel

Kent Johnson wrote:

On Fri, Jul 10, 2009 at 7:08 AM, Dave Angel wrote:
  

Alan Gauld wrote:



  

Or the translation program that translated the expression

Out of sight, out of mind

from English to Russian and back with the result:

Invisible, lunatic
  


  

Or the expression:
"The spirit is willing, but the flesh is weak"
to:
"The wine is good, but the meat is rotten"



These are fun but, according to snopes.com, they are probably urban
legend rather than fact:
http://www.snopes.com/language/misxlate/machine.asp

FWIW translate.google.com correctly translates both of the above from
English to Russian and back. I wonder if they have optimized for those
phrases?

Kent

  
I first heard the "spirit is willing" one about 30 years ago, from my 
father when he was studying Russian (written Russian, with the interest 
in reading technical materials), so I concur with Snopes evaluation.  
But I don't really care if it was true then or not.  It got some people 
to realize just how complex language automated translation might be.


As for present-day Google doing better on those, it's also possible that 
those idioms have been imported into Russian by now, so that there is a 
better translation possible.


My point is that in some languages, some concepts can't be literally 
translated, so some idiomatic usage may be needed.  I can only think of 
a lousy example right now, but Chinese apparently has no distinct verb 
forms for past, present, future.  So they rely on other words to 
indicate which they might mean.  And those clues might be far displaced 
from the verb in question.  And I frequently have talked to recent 
Chinese-American folk, who get the English for this wrong.  Until they 
learn to "think in English" some things are tricky.


And meatware is so much more powerful than software in these kinds of 
things, I'm amazed at how good computer translations have gotten.


I remember a computer translation of a camera review, where the English 
version kept referring to guns.  It took a few paragraphs to figure out 
they were talking about Canon.



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] getting image from url

2009-07-10 Thread Amit Sethi
Hi , I am trying to get  images from url

Their is  a  mail relating to it here :
"http://mail.python.org/pipermail/python-list/2001-October/108548.html";

but when i followed similar procedure :

>>> import urllib
>>>fp = 
>>>urllib.urlopen("http://en.wikipedia.org/wiki/File:Portrait_john_calvin.jpg";)
>>>img = cStringIO.StringIO(fp.read())
>>> Image.open(img)
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.5/site-packages/PIL/Image.py", line 1917, in open
raise IOError("cannot identify image file")
IOError: cannot identify image file

what is wrong?? how can I rectify...



-- 
A-M-I-T S|S
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Searching backwards from end of string

2009-07-10 Thread Angus Rodgers
I'm probably having a bit of an off-day, so please forgive me if
this is a really silly question (even for a beginner in Python)!

I'm working through the exercises for Chapter 6 of Wesley Chun's
book [incidentally, I tried to append another endorsement to the
list, but my use of Python rather than "+1" may have looked like
a typo or the work of a lunatic, or perhaps my post is just late
in appearing - anyway, another happy reader here!], and running
again into a difficulty which I "cheated" my way through earlier.

On the earlier occasion:

 "6-6 Strings. Create the equivalent of string.strip():  Take a
 string and remove all leading and trailing whitespace. (Use of
 string.*strip() defeats the purpose of this exercise.)"

I wrote:

from string import whitespace

def lstrip(s):
if s:
for i, c in enumerate(s):
if c not in whitespace:
break
return s[i:]
else:
return s

def rstrip(s):
return lstrip(s[::-1])[::-1]
# Note: far from maximally efficient (two unnecessary copies!)

def strip(s):
return lstrip(rstrip(s))

On the present occasion:

 "6-12 Strings. ...
 (b) Create another function called rfindchr() that will find the
 last occurrence of a character in a string.  Naturally this works
 similarly to findchr(), but it starts its search from the end of
 the input string.
 ..."

I thought I had better err in the opposite direction, so I wrote:

def findchr(strng, ch):
for i, c in enumerate(strng):
if c == ch:
return i
return -1

def rfindchr(strng, ch):
# Surely there's a neater (but still efficient) way?
n = len(strng)
for i in range(n - 1, -1, -1):
if strng[i] == ch:
return i
return -1

def subchr(strng, origchar, newchar):
chars = list(strng)
for i, c in enumerate(chars):
if c == origchar:
chars[i] = newchar
return ''.join(chars)

I've quoted all my code, in case it's all bad, but it's rfindchr()
that I'm particularly worried about.
-- 
Angus Rodgers
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] getting image from url

2009-07-10 Thread Emile van Sebille

On 7/10/2009 8:29 AM Amit Sethi said...

Hi , I am trying to get  images from url

Their is  a  mail relating to it here :
"http://mail.python.org/pipermail/python-list/2001-October/108548.html";

but when i followed similar procedure :


import urllib
fp = 
urllib.urlopen("http://en.wikipedia.org/wiki/File:Portrait_john_calvin.jpg";)
img = cStringIO.StringIO(fp.read())


Right here, try...

img.read()[:50]

... and it should become clear what the problem is...

HTH,

Emile

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching backwards from end of string

2009-07-10 Thread Robert Berman
I think you are looking for a complex solution.

How about the following example:


In [31]: s1='abcdeefghijkl'  #find last 'e'

In [32]: s2=s1[::-1]#reverses s1

In [33]: j=s2.find('e') #finds first 'e' in reversed string

In [36]: ind=len(s1)-j-1  #index into s1 where last occurrence of 'e' is

In [37]: ind
Out[37]: 5

In [38]: s1[ind]
Out[38]: 'e'

In [39]: s1
Out[39]: 'abcdeefghijkl' BINGO. Done.

Is that not a bit simpler


Robert

On Fri, 2009-07-10 at 16:24 +0100, Angus Rodgers wrote:
> I'm probably having a bit of an off-day, so please forgive me if
> this is a really silly question (even for a beginner in Python)!
> 
> I'm working through the exercises for Chapter 6 of Wesley Chun's
> book [incidentally, I tried to append another endorsement to the
> list, but my use of Python rather than "+1" may have looked like
> a typo or the work of a lunatic, or perhaps my post is just late
> in appearing - anyway, another happy reader here!], and running
> again into a difficulty which I "cheated" my way through earlier.
> 
> On the earlier occasion:
> 
>  "6-6 Strings. Create the equivalent of string.strip():  Take a
>  string and remove all leading and trailing whitespace. (Use of
>  string.*strip() defeats the purpose of this exercise.)"
> 
> I wrote:
> 
> from string import whitespace
> 
> def lstrip(s):
> if s:
> for i, c in enumerate(s):
> if c not in whitespace:
> break
> return s[i:]
> else:
> return s
> 
> def rstrip(s):
> return lstrip(s[::-1])[::-1]
> # Note: far from maximally efficient (two unnecessary copies!)
> 
> def strip(s):
> return lstrip(rstrip(s))
> 
> On the present occasion:
> 
>  "6-12 Strings. ...
>  (b) Create another function called rfindchr() that will find the
>  last occurrence of a character in a string.  Naturally this works
>  similarly to findchr(), but it starts its search from the end of
>  the input string.
>  ..."
> 
> I thought I had better err in the opposite direction, so I wrote:
> 
> def findchr(strng, ch):
> for i, c in enumerate(strng):
> if c == ch:
> return i
> return -1
> 
> def rfindchr(strng, ch):
> # Surely there's a neater (but still efficient) way?
> n = len(strng)
> for i in range(n - 1, -1, -1):
> if strng[i] == ch:
> return i
> return -1
> 
> def subchr(strng, origchar, newchar):
> chars = list(strng)
> for i, c in enumerate(chars):
> if c == origchar:
> chars[i] = newchar
> return ''.join(chars)
> 
> I've quoted all my code, in case it's all bad, but it's rfindchr()
> that I'm particularly worried about.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] getting image from url

2009-07-10 Thread Amit Sethi
I am sorry, I did not realize the problem was in the location .Ignore
the message

On Fri, Jul 10, 2009 at 9:19 PM, Emile van Sebille wrote:
> On 7/10/2009 8:29 AM Amit Sethi said...
>>
>> Hi , I am trying to get  images from url
>>
>> Their is  a  mail relating to it here :
>> "http://mail.python.org/pipermail/python-list/2001-October/108548.html";
>>
>> but when i followed similar procedure :
>>
> import urllib
> fp =
> urllib.urlopen("http://en.wikipedia.org/wiki/File:Portrait_john_calvin.jpg";)
> img = cStringIO.StringIO(fp.read())
>
> Right here, try...
>
>    img.read()[:50]
>
> ... and it should become clear what the problem is...
>
> HTH,
>
> Emile
>
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
A-M-I-T S|S
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] os.system and/or subprocess.call problem...

2009-07-10 Thread daychilde
I'm working on a program that calls another program recursively - this other
program reads in ini file and processes it; my program creates a number of
slightly different ini files and calls the other program for each one.

I can successfully generate the ini file. The problem is that the other
program doesn't seem to execute it correctly; or is unable to read its
contents. I'm not sure what's going on from the error it's giving me -
basically, it says there's nothing to do in the ini, so that's why I think
it's either not reading the ini, or perhaps it's being executed as the wrong
user or something. (Linux environment)

What's really gotten me is that if I take the command that I generate and
execute it manually, either on the shell command line, or even in the Python
interactive shell, it works. It's only when I call it programmatically that
it fails.

I've tried a number of different methods, and at this point, I'm a little
confused as to which did precisely what. For a while, I was getting a "file
is busy" error, which wasn't solved by putting a few seconds' delay .

So basically what I'm trying to do is:
-   Create a subdirectory (./timestamp/indexnumber - e.g.
./2009.07.08-11.55.24.12/1 - this works)
-   Write a file "bsf.ini" into that directory (this works)
-   Execute a program called "bluesky" from its directory, passing the
ini file along using the appropriate parameter (I'm definitely generating
the correct command to do this)

An example of the command that works, slightly changed to protect the
guilty, would be:
/home/isaac/bluesky/bluesky
-inifile=/home/isaac/loopy/2009.07.08-11.55.24.12/1/bsf.ini

('loopy' is my program. Not my choice, but it does 'loop' bluesky, so. hey.
Heh. I'm *going* loopy, but that's a different problem entirely!)

So when I execute the above on the command-line, it works perfectly. But
when I do it via an os.system or subproces.call, bluesky basically says
"hey, I found nothing to do here".

What do you think? Can it be executing bluesky in such a way that it can't
open the ini, or perhaps it's executing blueksy as a different user on the
system or something?

Sincerely,
-Isaac Eiland-Hall
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] thesaurus - translation, actually

2009-07-10 Thread Paul McGuire
My favorite rendition of this is in the related field of text-to-speech.  In
early Object Management Group days, OMG conference proceedings were
available as transcripts, but there was substantial delay in getting these
out.  An attempt to automate this with TTS software of the time was
discarded quickly - the first conference had a session track on
configuration management, and every mention of "version control" was
transcribed as "virgin control" - a dubious prospect in any event.

-- Paul


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.system and/or subprocess.call problem...

2009-07-10 Thread Steve Willoughby
On Fri, Jul 10, 2009 at 12:00:11PM -0500, daychi...@gmail.com wrote:
> I'm working on a program that calls another program recursively - this other

Actually it sounds like you're calling it iteratively, not recursively.

> I can successfully generate the ini file. The problem is that the other
> program doesn't seem to execute it correctly; or is unable to read its
> contents. I'm not sure what's going on from the error it's giving me -

>From what you write in here, my first thought is that the ini file
isn't being flushed out to disk before the subprocess starts up and
tries to read it.

Are you either calling .flush() or .close() or something
equivalent BEFORE starting the subprocess?

When you start the subprocess, is it being started in the directory
you think it is?

-- 
Steve Willoughby|  Using billion-dollar satellites
st...@alchemy.com   |  to hunt for Tupperware.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.system and/or subprocess.call problem...

2009-07-10 Thread Bill Campbell
On Fri, Jul 10, 2009, daychi...@gmail.com wrote:
>I'm working on a program that calls another program recursively - this other
>program reads in ini file and processes it; my program creates a number of
>slightly different ini files and calls the other program for each one.
>
>I can successfully generate the ini file. The problem is that the other
>program doesn't seem to execute it correctly; or is unable to read its
>contents. I'm not sure what's going on from the error it's giving me -
>basically, it says there's nothing to do in the ini, so that's why I think
>it's either not reading the ini, or perhaps it's being executed as the wrong
>user or something. (Linux environment)

Are you closing or flushing the output file before starting the subprocess?

Bill
-- 
INTERNET:   b...@celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
Voice:  (206) 236-1676  Mercer Island, WA 98040-0820
Fax:(206) 232-9186  Skype: jwccsllc (206) 855-5792

Thou shalt not steal, except by majority vote.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.system and/or subprocess.call problem...

2009-07-10 Thread daychilde
: Actually it sounds like you're calling it iteratively, not recursively.

:blush: Indeed.
 
: From what you write in here, my first thought is that the ini file
: isn't being flushed out to disk before the subprocess starts up and
: tries to read it.
: 
: Are you either calling .flush() or .close() or something
: equivalent BEFORE starting the subprocess?

self.filename = 'bsf.ini'
self.fullpath = self.thispath + self.filename
self.fh = open(self.fullpath, 'w')
self.fh.write(self.bsf_ini)
self.fh.close

Which doesn't show where the vars come from, but I am closing the file
first.

: When you start the subprocess, is it being started in the directory
: you think it is?

Well... I know that when I use os.system to create a directory, it starts in
cwd, which in this case is /home/isaac/loopy/ -- I create a directory with
the timestamp as the name, and successfully write out the bsf.ini files into
subfolders underneath it... so I think I'm confident that, at least when I
use os.system, it executes in cwd -- but I specific the path to the command,
so I think that doesn't matter anyway, e.g.:

/home/isaac/bluesky/bluesky
--inifile=/home/isaac/loopy/[timestamp]/12/bsf.ini

And I know the above is valid otherwise, as I have put in a print statement
and copied the actual line I generated and it executed fine... :)

Thank you for your reply; I appreciate all help I get on this. :) -Isaac

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.system and/or subprocess.call problem...

2009-07-10 Thread Steve Willoughby
On Fri, Jul 10, 2009 at 12:22:24PM -0500, daychi...@gmail.com wrote:
> self.filename = 'bsf.ini'
> self.fullpath = self.thispath + self.filename
> self.fh = open(self.fullpath, 'w')
> self.fh.write(self.bsf_ini)
> self.fh.close
> 
> Which doesn't show where the vars come from, but I am closing the file
> first.

Actually, no, it doesn't.  You forgot the () which are needed to 
actually _call_ the close method on the last line.

   self.fh.close

is an expression which evaluates to the close method object
belonging to the file object self.fh belonging to the object 
instance in play here.

   self.fh.close()

on the other hand, takes that method and calls it, and evaluates
to whatever that method call returns.


> : When you start the subprocess, is it being started in the directory
> : you think it is?
> 
> Well... I know that when I use os.system to create a directory, it starts in
> cwd, which in this case is /home/isaac/loopy/ -- I create a directory with
> the timestamp as the name, and successfully write out the bsf.ini files into
> subfolders underneath it... so I think I'm confident that, at least when I
> use os.system, it executes in cwd -- but I specific the path to the command,
> so I think that doesn't matter anyway, e.g.:

Ok, that sounds good.

> 
> /home/isaac/bluesky/bluesky
> --inifile=/home/isaac/loopy/[timestamp]/12/bsf.ini
> 
> And I know the above is valid otherwise, as I have put in a print statement
> and copied the actual line I generated and it executed fine... :)
> 
> Thank you for your reply; I appreciate all help I get on this. :)
> -Isaac
> 

-- 
Steve Willoughby|  Using billion-dollar satellites
st...@alchemy.com   |  to hunt for Tupperware.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.system and/or subprocess.call problem...

2009-07-10 Thread Emile van Sebille

On 7/10/2009 10:24 AM daychi...@gmail.com said...

: Actually it sounds like you're calling it iteratively, not recursively.

:blush: Indeed.
 
: From what you write in here, my first thought is that the ini file

: isn't being flushed out to disk before the subprocess starts up and
: tries to read it.
: 
: Are you either calling .flush() or .close() or something

: equivalent BEFORE starting the subprocess?

self.filename = 'bsf.ini'
self.fullpath = self.thispath + self.filename
self.fh = open(self.fullpath, 'w')
self.fh.write(self.bsf_ini)
self.fh.close

Which doesn't show where the vars come from, but I am closing the file
first.


Are you?  If it reads as you've pasted it doesn't.  I think you'll want

self.fh.close()

Emile

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.system and/or subprocess.call problem...

2009-07-10 Thread daychilde
: > self.fh.close
: >
: > Which doesn't show where the vars come from, but I am closing the
: file
: > first.
: 
: Actually, no, it doesn't.  You forgot the () which are needed to
: actually _call_ the close method on the last line.
: 
:self.fh.close
: 
: is an expression which evaluates to the close method object
: belonging to the file object self.fh belonging to the object
: instance in play here.
: 
:self.fh.close()
: 
: on the other hand, takes that method and calls it, and evaluates
: to whatever that method call returns.

I don't know whether to be happy it's a stoopid-newbie mistake or not... :)

I am extremely grateful, however, for the help - and I already see one more
reply pointing this out, so to Emile as well, and anyone else -- my hearty
thanks. Think I'll go curl up in a ball in the corner for a while now. ;-)

-Isaac

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] My code to update database

2009-07-10 Thread Eduardo Vieira
Hello! I have the code below to update a database from a csv file. I
have tested one time and it has worked fine, but I'm a bit fearful
that it should work right as I am updating a database and don't want
to cause troubles into the system.
Is this code safe for my personal use?
the update code is in a function, but the rest of the code to connect
and disconnect is outside the function. I thought this was a good idea
because for each line iterated in the csv file, there is a call to the
function to update the database with the data from the csv file. So,
using the 'global' inside the function is ok, or maybe not?


# --- Code starts here ---

import csv
import dbi
import odbc

myconn = odbc.odbc('DSN=MKPT01')
mycursor = myconn.cursor()

def inventory_update(partnumber, quantity, warehouse='00'):
"""Updates a given part number with the corrected quantity"""
global mycursor
mycursor.execute("""UPDATE INVENTORY SET ONHAND = ?
WHERE CODE = ? AND WHSE = ?

""", [quantity, partnumber, warehouse])


if __name__ == "__main__":

csvreader = csv.reader(open('Inventory_tracker.csv', 'rb'),
dialect = 'excel')

for pnumber, qty in csvreader:
print "%s has now %s items in stock" % (pnumber, qty)
inventory_update(pnumber, qty)

mycursor.close()
myconn.commit()
myconn.close()

# --- End ---

I'd appreciate your feedback.

Eduardo
www.expresssignproducts.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] My code to update database

2009-07-10 Thread Emile van Sebille

On 7/10/2009 11:29 AM Eduardo Vieira said...

Hello! I have the code below to update a database from a csv file. I
have tested one time and it has worked fine, but I'm a bit fearful
that it should work right as I am updating a database and don't want
to cause troubles into the system.
Is this code safe for my personal use?


Looks OK to me -- note one small change I'd make (move myconn and 
mycursor to after __main__ test) , but even that's not critical.



the update code is in a function, but the rest of the code to connect
and disconnect is outside the function. I thought this was a good idea
because for each line iterated in the csv file, there is a call to the
function to update the database with the data from the csv file. So,
using the 'global' inside the function is ok, or maybe not?


Looks like you don't need the global at all.  Have you tried without it?


Emile

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching backwards from end of string

2009-07-10 Thread Angus Rodgers
On Fri, 10 Jul 2009 11:57:21 -0400, Robert Berman
 wrote:

>I think you are looking for a complex solution.

Hardly.

>How about the following example:
>
>
>In [31]: s1='abcdeefghijkl'  #find last 'e'
>
>In [32]: s2=s1[::-1]#reverses s1
>
>In [33]: j=s2.find('e') #finds first 'e' in reversed string
>
>In [36]: ind=len(s1)-j-1  #index into s1 where last occurrence of 'e' is
>
>In [37]: ind
>Out[37]: 5
>
>In [38]: s1[ind]
>Out[38]: 'e'
>
>In [39]: s1
>Out[39]: 'abcdeefghijkl' BINGO. Done.
>
>Is that not a bit simpler

I did explain (perhaps at too great a length, or with too many
irrelevancies):

>On Fri, 2009-07-10 at 16:24 +0100, Angus Rodgers wrote:
>> [...]
>> On the earlier occasion:
>> [...]
>> I wrote:
>> [...]
>> def rstrip(s):
>> return lstrip(s[::-1])[::-1]
>> # Note: far from maximally efficient (two unnecessary copies!)
>> [...]
>> On the present occasion:
>> [...]
>> I thought I had better err in the opposite direction, so I wrote:
>> [...]
>> def rfindchr(strng, ch):
>> # Surely there's a neater (but still efficient) way?
>> n = len(strng)
>> for i in range(n - 1, -1, -1):
>> if strng[i] == ch:
>> return i
>> return -1

I don't even think that's "complicated" (just ugly and clumsy).

I just wondered if there were some simplifying feature of Python
that I had either forgotten or not learned about yet.  Python code
(even mine!) is usually neater than this.

I know efficiency is not always a major concern (and it certainly
isn't of any practical importance in a toy example like this),
but it seems downright profligate to make a reversed copy of a
string just in order to avoid searching it backwards, and to make
use of a nifty notation like "[::-1]" - even though my own first 
instinct is to do exactly that, to save "development time", and
to make use of a previous solution.
-- 
Angus Rodgers
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] My code to update database

2009-07-10 Thread Eduardo Vieira
On Fri, Jul 10, 2009 at 12:51 PM, Emile van Sebille wrote:
> On 7/10/2009 11:29 AM Eduardo Vieira said...
>>
>> Hello! I have the code below to update a database from a csv file. I
>> have tested one time and it has worked fine, but I'm a bit fearful
>> that it should work right as I am updating a database and don't want
>> to cause troubles into the system.
>> Is this code safe for my personal use?
>
> Looks OK to me -- note one small change I'd make (move myconn and mycursor
> to after __main__ test) , but even that's not critical.
Well, I thought in the case I needed to import this module then I'd
have to put it there, right?

>
>> the update code is in a function, but the rest of the code to connect
>> and disconnect is outside the function. I thought this was a good idea
>> because for each line iterated in the csv file, there is a call to the
>> function to update the database with the data from the csv file. So,
>> using the 'global' inside the function is ok, or maybe not?
>
> Looks like you don't need the global at all.  Have you tried without it?
>
>
Oh, yeah, I was getting confuse on that... probably because a another
case where I did need to use the 'global' declaration
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] My code to update database

2009-07-10 Thread Emile van Sebille

On 7/10/2009 1:03 PM Eduardo Vieira said...

On Fri, Jul 10, 2009 at 12:51 PM, Emile van Sebille wrote:

On 7/10/2009 11:29 AM Eduardo Vieira said...

Hello! I have the code below to update a database from a csv file. I
have tested one time and it has worked fine, but I'm a bit fearful
that it should work right as I am updating a database and don't want
to cause troubles into the system.
Is this code safe for my personal use?

Looks OK to me -- note one small change I'd make (move myconn and mycursor
to after __main__ test) , but even that's not critical.

Well, I thought in the case I needed to import this module then I'd
have to put it there, right?


Yes -- but that's the place you're shutting things down at, so it made 
sense to me to do the setup in the same spot.  Certainly if you import 
the module, you'd not expect the shutdown code to be implemented 
external to your module, so some restructuring would be needed to 
convert this to utility status.


Emile

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching backwards from end of string

2009-07-10 Thread Robert Berman


On Fri, 2009-07-10 at 20:55 +0100, Angus Rodgers wrote:
> On Fri, 10 Jul 2009 11:57:21 -0400, Robert Berman
>  wrote:
> 
> >I think you are looking for a complex solution.
> 
> Hardly.
In my opinion your code w was overly complex for what you were
attempting to do.  I would not be so presumptuous to tell you that you
should  change it. I do think you asked for a simple method to solve a
specific problem. That is what I offered; nothing else.
> >How about the following example:
> >
> >
> >In [31]: s1='abcdeefghijkl'  #find last 'e'
> >
> >In [32]: s2=s1[::-1]#reverses s1
> >
> >In [33]: j=s2.find('e') #finds first 'e' in reversed string
> >
> >In [36]: ind=len(s1)-j-1  #index into s1 where last occurrence of 'e' is
> >
> >In [37]: ind
> >Out[37]: 5
> >
> >In [38]: s1[ind]
> >Out[38]: 'e'
> >
> >In [39]: s1
> >Out[39]: 'abcdeefghijkl' BINGO. Done.
> >
> >Is that not a bit simpler
> 
> I did explain (perhaps at too great a length, or with too many
> irrelevancies):
> 
> >On Fri, 2009-07-10 at 16:24 +0100, Angus Rodgers wrote:
> >> [...]
> >> On the earlier occasion:
> >> [...]
> >> I wrote:
> >> [...]
> >> def rstrip(s):
> >> return lstrip(s[::-1])[::-1]
> >> # Note: far from maximally efficient (two unnecessary copies!)
> >> [...]
> >> On the present occasion:
> >> [...]
> >> I thought I had better err in the opposite direction, so I wrote:
> >> [...]
> >> def rfindchr(strng, ch):
> >> # Surely there's a neater (but still efficient) way?
> >> n = len(strng)
> >> for i in range(n - 1, -1, -1):
> >> if strng[i] == ch:
> >> return i
> >> return -1
> 
> I don't even think that's "complicated" (just ugly and clumsy).

I disagree. For the question asked, the solution is complicated. 
A nifty 'notation like "[::-1]"' is an example of something called
slicing which you will find very well explained in 6.1 of CORE PYTHON
PROGRAMMING.  I thought that you had reviewed this since it precedes the
questions in Chapter 6. It is a very handy tool for not only strings,
but lists and dictionaries as well.

> 
> I just wondered if there were some simplifying feature of Python
> that I had either forgotten or not learned about yet.  Python code
> (even mine!) is usually neater than this.
> 
> I know efficiency is not always a major concern (and it certainly
> isn't of any practical importance in a toy example like this),
> but it seems downright profligate to make a reversed copy of a
> string just in order to avoid searching it backwards, and to make
> use of a nifty notation like "[::-1]" - even though my own first 
> instinct is to do exactly that, to save "development time", and
> to make use of a previous solution.

In any case, whether you choose to incorporate my suggestion or not, I
hope you will take some time and experiment with it if only because it's
a fun type of solution.

Robert

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] thesaurus

2009-07-10 Thread ALAN GAULD




> right now, but Chinese apparently has no distinct verb forms for past, 
> present, 
> future.  So they rely on other words to indicate which they might mean. 


Chinese also has the problem of relying on intonation to distinguish between 
identically spelled words. We have the same in English - bow(on stage) v bow 
(as in arrows), but there are lots of these things in Chinese making 
translation 
of written language almost wholly context dependant, and therefore very 
difficult for a machine.

Alan G
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Trickier exercise: convert string to complex number

2009-07-10 Thread Angus Rodgers
Wesley Chun, /Core Python Programming/, Ex. 6-13:

 "[...] An atoc() was never implemented in the string module, so
 that is your task here.  atoc() takes a single string as input,
 a string representation of a complex number [...] and returns
 the equivalent complex number object with the given value [...]"

   (retention: 1 day)
   (retention: 1 day)
(helper functions for user input)

The main functions are short enough to post here, I think, but
there are many explanatory and apologetic comments in the first
file above; also, I would welcome (with a grimace!) any comments
as to whether I am developing a cranky or baroque style (as I'm
working very much on my own, apart from whatever feedback I can
get here), and such misdemeanours are more likely to be noticed
in the second (and longer) of the two files above.

from string import whitespace

def no_spaces(str):
return ''.join([ch for ch in str if ch not in whitespace])

def atoc(num):
"""Convert string representation to complex number."""
num = no_spaces(num)
n = len(num)
if not n:
raise ValueError
# Ignore first character
for i, ch in enumerate(num[1:]):
if ch == 'j':
# Must be end of string, else invalid
if i != n - 2:
raise ValueError
return complex(0.0, float(num[:-1]))
if ch in '+-' and num[i] not in 'eE':
return complex(float(num[:i + 1]),
   float(num[i + 1:-1]))
return complex(float(num), 0.0)

-- 
Angus Rodgers
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trickier exercise: convert string to complex number

2009-07-10 Thread Rich Lovely


On 11 Jul 2009, at 03:15, Angus Rodgers  wrote:


Wesley Chun, /Core Python Programming/, Ex. 6-13:

"[...] An atoc() was never implemented in the string module, so
that is your task here.  atoc() takes a single string as input,
a string representation of a complex number [...] and returns
the equivalent complex number object with the given value [...]"

   (retention: 1 day)
   (retention: 1 day)
(helper functions for user input)

The main functions are short enough to post here, I think, but
there are many explanatory and apologetic comments in the first
file above; also, I would welcome (with a grimace!) any comments
as to whether I am developing a cranky or baroque style (as I'm
working very much on my own, apart from whatever feedback I can
get here), and such misdemeanours are more likely to be noticed
in the second (and longer) of the two files above.

from string import whitespace

def no_spaces(str):
   return ''.join([ch for ch in str if ch not in whitespace])

def atoc(num):
   """Convert string representation to complex number."""
   num = no_spaces(num)
   n = len(num)
   if not n:
   raise ValueError
   # Ignore first character
   for i, ch in enumerate(num[1:]):
   if ch == 'j':
   # Must be end of string, else invalid
   if i != n - 2:
   raise ValueError
   return complex(0.0, float(num[:-1]))
   if ch in '+-' and num[i] not in 'eE':
   return complex(float(num[:i + 1]),
  float(num[i + 1:-1]))
   return complex(float(num), 0.0)

--  
Angus Rodgers

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


This would probably be considered cheating, but there _is_ actually a  
atoc() (of sorts) in the 2.6 stdlib. It's called ast.literal_eval().   
It will take a string representing ANY python literal, and SAFELY  
return it's value.


Why has no one here spoted this before?

---
Rich "RoadieRich" Lovely
There are 10 types of people in the world: those who know binary,  
those who do not, and those who are off by one.


(Sent from my iPod - please allow me a few typos: it's a very small  
keyboard)


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trickier exercise: convert string to complex number

2009-07-10 Thread Lie Ryan
Angus Rodgers wrote:
> Wesley Chun, /Core Python Programming/, Ex. 6-13:
> 
>  "[...] An atoc() was never implemented in the string module, so
>  that is your task here.  atoc() takes a single string as input,
>  a string representation of a complex number [...] and returns
>  the equivalent complex number object with the given value [...]"

It's true that atoc() was never implemented in the string module, but
the builtin complex() does the same thing (and more).

>    (retention: 1 day)
>    (retention: 1 day)
> (helper functions for user input)
>
> The main functions are short enough to post here, I think, but
> there are many explanatory and apologetic comments in the first
> file above; also, I would welcome (with a grimace!) any comments
> as to whether I am developing a cranky or baroque style (as I'm
> working very much on my own, apart from whatever feedback I can
> get here), and such misdemeanours are more likely to be noticed
> in the second (and longer) of the two files above.
> 
> from string import whitespace
> 
> def no_spaces(str):
> return ''.join([ch for ch in str if ch not in whitespace])
> 
> def atoc(num):
> """Convert string representation to complex number."""
> num = no_spaces(num)
> n = len(num)
> if not n:
> raise ValueError
> # Ignore first character
> for i, ch in enumerate(num[1:]):
> if ch == 'j':
> # Must be end of string, else invalid
> if i != n - 2:
> raise ValueError
> return complex(0.0, float(num[:-1]))
> if ch in '+-' and num[i] not in 'eE':
> return complex(float(num[:i + 1]),
>float(num[i + 1:-1]))
> return complex(float(num), 0.0)
> 

Err... what's the question? Are you asking for style checking or the
mentioned "bugs" in the comments?


===
_const_func = lambda c : (lambda x : c)
...
def get_val(typ, prompt=None, valid=_const_func(True)):
   ...

I think that is an over-generalisation. It is much simpler to read
def get_val(typ, prompt=None, valid=lambda x: True):

because other people reading your code might not know what _const_func
do (whether it is simply returning a lambda or it does something more
complex).
===

> # A bug in this program is that, by indiscriminately removing all
> #
> # whitespace before processing, it fails to catch certain errors,
> #
> # e.g. " - 1 2 " will be passed to float("-12").  Correcting this
> #
> # bug is likely to make the program considerably more ... complex.

You can avoid that bug by not stripping whitespaces. Ignore them inside
the loop (put if ch == '': break) and before passing the number to
float, compare the number's length before and after the whitespace is
stripped. Not really considerably more complex...

===
> # (It would seem to be more sensible to learn about the regular
> #
> # expressions module than to complicate this simplistic program.)

With regex, you'll just "simply" need something like:

>>> import re
>>> pat = r'({s})??(?:({f})({s})?)??({f}j)?$'
>>> pat = pat.format(f=r'(?:\d*\.?\d*)', s=r'[+-]')
>>>
>>> print pat
([+-])??(?:((?:\d*\.?\d*))([+-])?)??((?:\d*\.?\d*)j)?$
>>>
>>> tests = ['', '10', '+10', '-10', '10.', '+10.', '-10.', '.4', '+.4',
'-.4', '10.4', '+10.4', '-10.4', '10j', '+10j', '-10j', '10.j', '+10.j',
'-10.j', '.4j', '+.4j', '-.4j', '10.4j', '+10.4j', '-10.4j', '10+10j',
'+10+10j', '-10+10j', '10.+10j', '+10.+10j', '-10.+10j', '10.4+10j',
'+10.4+10j', '-10.4+10j', '.4+10j', '+.4+10j', '-.4+10j', '10+10.4j',
'10.4+10.4j', '+10.4+10.4j', '+10.4-10.4j']
>>> for t in tests:
... print t, re.match(pat, t).groups()
...
 (None, None, None, None)
10 (None, '10', None, None)
+10 ('+', '10', None, None)
-10 ('-', '10', None, None)
10. (None, '10.', None, None)
+10. ('+', '10.', None, None)
-10. ('-', '10.', None, None)
.4 (None, '.4', None, None)
+.4 ('+', '.4', None, None)
-.4 ('-', '.4', None, None)
10.4 (None, '10.4', None, None)
+10.4 ('+', '10.4', None, None)
-10.4 ('-', '10.4', None, None)
10j (None, None, None, '10j')
+10j (None, '', '+', '10j')
-10j (None, '', '-', '10j')
10.j (None, None, None, '10.j')
+10.j (None, '', '+', '10.j')
-10.j (None, '', '-', '10.j')
.4j (None, None, None, '.4j')
+.4j (None, '', '+', '.4j')
-.4j (None, '', '-', '.4j')
10.4j (None, None, None, '10.4j')
+10.4j (None, '', '+', '10.4j')
-10.4j (None, '', '-', '10.4j')
10+10j (None, '10', '+', '10j')
+10+10j ('+', '10', '+', '10j')
-10+10j ('-', '10', '+', '10j')
10.+10j (None, '10.', '+', '10j')
+10.+10j ('+', '10.', '+', '10j')
-10.+10j ('-', '10.', '+', '10j')
10.4+10j (None, '10.4', '+', '10j')
+10.4+10j ('+', '10.4', '+', '10j')
-10.4+10j ('-', '10.4', '+', '10j')
.4+10j (None, '.4', '+', '10j')
+.4+10j ('+', '.4', '+', '10j')
-.4+10j ('-', '.4', '+', '10j')
10+10.4j (None, '10', '+', '10.4j')
10.4+10.4j (None, '10.4', '+', '10.4j')
+10.4+10.4j ('+', '10.4', '+', '10.4j')
+10.4-10.4j ('+', '