Re: Just Getting Started with Python on MS XP Pro

2007-01-05 Thread DouhetSukd
Wise choice + welcome to the club.

Though Python is open source and well appreciated on Linux, I think you
will find that most people in this newsgroup will be fairly courteous
about _your_ choice of platform.  Some will not know about the weird
process forking stuff on windows and helpfully suggest that 'if you
were to use a real OS...'.  But in reality Python is just as happy on
XP as on Linux and the lack of scripting/shell alternatives on XP makes
it all the more useful there.

The only real XP drawback is that Python is not bundled on Windows,
while it is included with OS X and most (all?) Linux distros.

So, giving a *.py program to another XP user means little by itself, it
needs to be either packaged in an exe (see py2exe) or you need to get
your buddy to install python on their machine.


In descending order of cheapness/usefullness.

1.  download python + work through the tutorial.  well, maybe not all
of it, but with pythonwin around, you can try out significant snippets
quickly.


2.  use any ol' text editor that _you_ are familiar with, save to file,
and python  under DOS.  later on you can always pick an editor.
i prefer eclipse + pydev, yes, even on windows.

personally, i find pythonwin _great_ to test out code interactively,
mediocre to write lots of code with and occasionally handy to debug
code in.

if you hate typing python  under DOS, then I guess you will have
to run programs from pythonwin.


3.  internet

this newsgroup is very informative.

dive into python, pretty good net resource

www.diveintopython.org



4.  books:

Learning Python, isbn 0596002815, is pretty good.

Python Programming on Win32, isbn 1565926218, is good, if a bit dated
(2000, covers COM but no .Net)

In depth Python - Python in a Nutshell, isbn 0596100469


5.  GUI stuff.

wxPython.  If, like me, you hate handcoding everything and want a VB
drag&drop clone you will have to look around for someone else's advice
- there are several such editors that do wxPython but I have never
found anything entirely to my liking.  I am sure others will chime in
with their recommendations.


6.  Database stuff.

Personally, working on MS SQL, I vouch for mxODBC - shareware, which I
used for years without paying, until I decided the guy had definitely
earned my $75.

http://www.egenix.com/files/python/eGenix-mx-Extensions.html


7.  Prepping *.py programs for distribution to users w.o. Python

py2exe - www.py2exe.org/

Best o' luck.

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


Re: help on object programing

2007-08-17 Thread DouhetSukd

> how can i define my variables so that there are valid outside the
> class???

Not to be obnoxious, but your sample code has a number of fairly big
conceptual issues (like subclassing self and assigning 32 at the big
class level and printing 'list' which is a built-in type).  Been there
myself - it took me a while to understand class vs. instance
variables.  You are also using fairly advanced techniques such as
embedded classes which look above a newbie level.

I took the liberty to comment and "fix" up your code a bit so that it
runs:

#classes either inherit or not and signify that in parenthesis.
inheriting 'self' makes no sense
#for a class declaration.  but it does make perfect sense to have
'self' as a param to a class method (def)

class big:

#class-level variable
x = 32

#changed to mylist to avoid confusion with list built-in.
mylist = []

#this is a normal instance method - 'self' refers to the class
instance you just created.
def inside (self):

#is this really what you wanted?  an embedded class -
syntaxically correct, but not used often
class small: # a new class defined inside the first

y = 348
#ok, now I am referring to the mylist variable associated
(bound in python-speak) to the big class.
#y is defined here so no need to do anything
big.mylist.append(y) # send the value to first list
#same with big.x
big.mylist.append(big.x)


#instantiate the class, because you are calling an instance method
(i.e. you need to have created an instance to use that method)
#call the call
mybig = big().inside()

#refer to the mylist variable declared at the class, not instance
level.
#class level means any other calls you make will alter that variable
print 'my class level mylist variable:',big.mylist

console output:

my class level mylist variable: [348, 32]

Can you perhaps rephrase your requirements to indicate what you want
to achieve?

Strictly speaking, it looks like you could do this:

class Big:
def getlist(self):
   return [348,32]

mylist =Big().getlist()

That's probably not what you were asking for, but it does express the
results you would get out of your code, especially as you are not
passing in any significant parameters to the 'inside' function.

OK, perhaps a bit more useful.

#no inheritance - could also be class Big(object) where object is the
python "root class"
class Big:

   #initialize the class level to be empty
   myclasslist = []
   def __init__(self):
  #initialize the instance level variable to be empty
  self.myinstancelist = []

   def appendAndGet(self,x,y):
  #modify the instance's "personal" list
  self.myinstancelist.append(x)
  self.myinstancelist.append(y)
  #will now modify shared class-level variable.
  Big.myclasslist.append(x)
  Big.myclasslist.append(y)
  return self.myinstancelist


print "Big.myclasslist without any instances around:", Big.myclasslist


bigA = Big()
result = bigA.appendAndGet(348,32)
print "result #1:", result
print "Big.myclasslist:", Big.myclasslist

bigB = Big()
result = bigB.appendAndGet(11,22)
print "result #2:", result

#and the instance also still has its myinstancelist around
print "same as result #2:", bigB.myinstancelist

print "Big.myclasslist:", Big.myclasslist

console output:

D:\user\workspace\vg\tmptesting>testc.py
my class level mylist variable: [348, 32]
Big.myclasslist without any instances around: []
result #1: [348, 32]
Big.myclasslist: [348, 32]
result #2: [11, 22]
same as result #2: [11, 22]
Big.myclasslist: [348, 32, 11, 22]

Try perhaps Dive Into Python's class intro:

www.diveintopython.org/object_oriented_framework/defining_classes.html

Cheers


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


funny little 190 lines command line math tutor I wrote for my 7-year old.

2007-09-14 Thread DouhetSukd
Sadly lacking in multi-media bells and whistles.  But my daughter
actually likes playing with it.

Coded on windows, but no reason it shouldn't work on Linux/OS X.

(hopefully the indentation won't be too mangled by usenet.  apologies
in advance if that is the case)

Enjoy.

Sample session:

D:\user\python>mathtester.py -1 3 -o /+ -r 2
Hello, I am your friendly computer.  I have a math quiz for you

 Problem #1

 1 +  2 = 3
Answered: 3.  Correct.

 Problem #2

 3 +  3 = 6
Answered: 6.  Correct.


Congratulations, you got  2 right out of  2


code:


"""
mathtester.py -h for more help .

HELPS YOUR KIDS TO LEARN MATH WITH INTERACTIVE PROMPTS.  EXAMPLE:

Hello, I am windoze, your friendly computer.  I have a math quiz for
you

 Problem #0

 4 -  3 = 1
Answered: 1.  Correct.

 Problem #1

 8 -  6 = 14
Answered:14.  Wrong.  Correct
answer: 2

This will pick two numbers, each between 0 and 10.  It will either add
or substract them.  Any questions with solutions less than zero
or greater than 20 will be rejected and re-created.

You get this by running it with all defaults.  i.e.

c:\>python mathtester.py


to get something like doing the multiplication of 1 to 3 times 10, run

c:\>python mathtester -o * -1 3 -2 10 -H 30

only multiplication '*' will be used, number #1 will be between 0 and
3.  number #2 will be between 0 and 10.  answers greater than 30 will
be rejected.

"""

import os, sys, optparse, random

_module_doc = __doc__

class Writer:
"""write to file and output to console"""
def  __init__(self,fout):
self.fout = fout
def __call__(self,s,echoconsole=True):
self.fout.write("\n" + s.replace("\t",""))
if echoconsole:
print s

class Worker:

fout = None
filename = "test.txt"
trivial_tolerance_percentage = 40
accepted_operators = "+-*"

def formatoptions(self):
"""most of the work is already done by optparser"""
#filter on acceptable operators.  exit if none found.
self.operators = [i for i in self.options.operators if i in
self.accepted_operators]
if not self.operators:
print ERROR_MSG_OPERATORS % {"supported" :
self.accepted_operators}
sys.exit()
#both number range limits are equal.
if not self.options.numberRange2:
self.options.numberRange2 = self.options.numberRange


def  __init__(self):
self.fout = open(self.filename,"w")
Worker.writer = Writer(self.fout)
self.formatoptions()
self.asked = self.correct = 0
self.set_asked = set()

def process(self):
"""main loop - prints greetings, loops on questions, print
result summary and exits"""
try:
  self.writer(GREETING)
  [self.doTest(cntr) for cntr in
range(0,self.options.repetitions)]
except KeyboardInterrupt:
  pass
self.writer(FAREWELL % vars(self))
return True

def doTest(self,number):
"""the workhorse function.  randomly picks a question + vets
the solution
then asks the question and checks the answer"""
self.writer("\n Problem #%s" % (number+1))

while True:
#pick random numbers and operator
number1  = random.randint(0,self.options.numberRange)
number2  = random.randint(0,self.options.numberRange2)
operator =
self.operators[random.randint(0,len(self.operators)-1)]

if number1 < 2 or number2 < 2 and
random.randint(1,100)>self.trivial_tolerance_percentage:
#potentially reject trivial problems consisting of
zeros and ones.
continue

#flip a coin and put number #1 either right or left -
#remember that the number ranges can be unequal so there
is a difference
if random.randint(1,2) % 2:
problem  = "%2s %s %2s" % (number1,operator,number2)
else:
problem  = "%2s %s %2s" % (number2,operator,number1)

#use eval to get the expected solution
solution = eval(problem)

#solution within accepted bounds? if not, build another
problem
if not ((solution >= self.options.minSolution) and
(solution <= self.options.maxSolution)):
continue

#don't ask the same question multiple times...
if problem in self.set_asked:
continue
self.set_asked.add(problem)

#answers other than digits will be ignored and the prompt
will repeat
while True:
try:
prompt = "\n\t\t" + problem + " = "
self.writer(prompt,False)
answer = raw_input(prompt)

Re: funny little 190 lines command line math tutor I wrote for my 7-year old.

2007-09-14 Thread DouhetSukd
Ok, it does look a bit mangled.  I re-posted it on www.pastebin.com,
at http://python.pastebin.com/m7b1f9ab5.

Cheers

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


Re: "once" assigment in Python

2007-09-14 Thread DouhetSukd
Agree that what you are looking for may not be a good idea.  So make
sure you don't shoot yourself in the foot with it.  You should
probably look into your problem some more.

>>> def once(obj,attrname,value):
... if hasattr(obj,attrname):
... return
... else:
... setattr(obj,attrname,value)
...
>>> class Foo:
... pass
...
>>> foo = Foo()
>>> once(foo,"a",1)
>>> foo.a
1
>>> once(foo,"b",2)
>>> foo.a
1
>>> def m1(self):
... print "i am m1"
...
>>> def m2(self):
... print "i am m2"
...
>>> once(Foo,"mx",m1)
>>> foo.mx()
i am m1
>>> once(Foo,"mx",m2)
>>> foo.mx()
i am m1
>>>

This is very generic code, but you could make it specific to a class
and an attribute.  If so look into properties.

class Foo2:

  def _setMyAttr(self,value):
 if hasattr(self,"_myAttr"):
   return
 self._myAttr = value

  def _getMyAttr(self):
 if not hasattr(self,"_myAttr"):
return "somedefaultvalue"
 return self._myAttr

  myAttr = property(_getMyAttr,_setMyAttr)

Note also :  stay away from __setattr__ until you know what you are
doing and
you know when to use self.__dict__ assignments.  Painful personal
experiences for me.

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


Re: Just bought Python in a Nutshell

2007-09-14 Thread DouhetSukd
I respectfully disagree with Shawn, in this case.

Don't skim Nutshell, unless you know very little Python, and even then
it is really the wrong book.  It is rather dry reading and provides
very little of the usual user-friendly introductions to language
features by solving simple problems.

Doesn't sound like that much of an endorsement, does it?  Well, in
fact, it is pretty much my most used Python book (out of 7 or 8
others).

If you read Alex's posts in this newsgroup, you'll see that he is one
of the most pragmatic and rigorous posters who usually contributes
code that elegantly and simply solves the issue at hand with the
minimum amount of clutter.

What Python in a Nutshell is really good at is showing you exactly
what Python is capable of doing, feature by feature, in a thoroughly
Pythonic way for the feature.  With code and exact implication.  For
example, I know Python well but I am kinda lacking in metaclass
comprehension.  If I were to write some non-trivial metaclasses I
would surely have his 3 or 4 pages open on my desk as I write code and
skim through other internet postings.  Those 3-4 pages have kinda made
my brain shrivel every time I've looked at them, but they are the
clearest overview I've seen of what is probably one of the hardest
Python features to understand.

For normal, easy-to-understand Python, Nutshell really dissects the
languages with new insight.  The information is dense, because each
word has its place and there very little filler.  That's why skimming
it does not work for me, I just don't have the requisite sustained
attention span.

So, although I read almost all other computer books like Shawn does, I
don't think it applies in this particular case.  When you have a
particular aspect of Python in mind, use Nutshell.  Read up on 'look
before you leap' in it if you really want a sample of how it is
written.

Cheers

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


Re: How to Start

2007-09-14 Thread DouhetSukd
On Sep 13, 4:02 pm, Nikita the Spider <[EMAIL PROTECTED]>
wrote:
> My $.02 for someone such as yourself
> is to deal with Python and as little else as possible. So write your
> code in a simple text editor like UltraEdit or Notepad

Second that opinion.  Use _your_ favorite basic text editor and run on
command line.  Don't clutter your attention with complex tools, yet,
Python's not J2EE for Pete's sake.  I started on Kedit, but mostly use
Eclipse + pydev now, with KEdit as a backup.

Do use one of the interactive interpreters (pythonwin, python prompts,
etc...) to try out one liners and short pieces of code.  But I've
never really liked them for writing full programs.

And I would just do the tutorial or Dive Into Python (http://
www.diveintopython.org/toc/index.html).  If you are as experienced as
you say, you should have very little trouble working through them,
really quickly (3-4 hours?) and you'll have a good tour of the
features.  I picked up Python on a Montreal to Vancouver flight, doing
just that.

For your problem domain.  Modules:  optparse, regular expressions.
Perhaps the "Text Processing in Python" book by Mertz.  I don't like
it much myself, but it does cover text processing in depth and it
refers to a number of existing specialized libraries.

Cheers

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


Re: Populating a dictionary, fast

2007-11-11 Thread DouhetSukd
On Nov 11, 7:35 am, Michael Bacarella <[EMAIL PROTECTED]> wrote:

> Tried that already.  No difference. :(

Not sure if it would make a difference, and it would imply re-
organizing your preceding lines, but what about doing the dictionary
build in one go, rather than incrementally?  Using the dict function,
which takes a list of (key,value) tuples.  I use it frequently as a
space-saver and it works well enough.  It may speed things up, I
dunno.  I had to break out your formatting in its own function and
that can't help too much.

Something like:

def fmt(line):
id,name = line.strip().split(':')
id = long(id)
return (id,name)

id2name = dict([fmt(line) for line in
iter(open('id2name.txt').readline,'')])

Cheers

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


Re: Populating a dictionary, fast

2007-11-11 Thread DouhetSukd
Ah, well, just noticed Ben's suggested this already.  Mind you, his
code, while correct in intent, does look a bit fishy (missing those
square brackets), so don't dismiss it just because you had trouble
running it (or mine).  Definitely worth a try and I'd be curious to
know if it makes a difference.

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


Re: How to get a set of keys with largest values?

2007-11-13 Thread DouhetSukd
On Nov 12, 1:07 am, Davy <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I have a dictionary with n elements, and I want to get the m(m<=n)
> keys with the largest values.
>
> For example, I have dic that includes n=4 elements, I want m=2 keys
> have the largest values)
> dic = {0:4,3:1,5:2,7:8}
> So, the the largest values are [8,4], so the keys are [7,0].
>
> Is there any fast way to implement this algorithm?
> Any suggestions are welcome!
>
> Best regards,
> Davy

#get a list of tuples, with value in 1st position, key second
li = [(value,key) for key, value in dic.items()]

#sort the list
li.sort()

m = 2
#grab the m highest values, from the end of the list
li_high_keys = [k for v, k in li[-m:]]

p.s. sorry if this ends up appearing multiple times, google groups can
be a bit cranky at times with postings.

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


Re: How to get a set of keys with largest values?

2007-11-13 Thread DouhetSukd
On Nov 12, 1:07 am, Davy <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I have a dictionary with n elements, and I want to get the m(m<=n)
> keys with the largest values.
>
> For example, I have dic that includes n=4 elements, I want m=2 keys
> have the largest values)
> dic = {0:4,3:1,5:2,7:8}
> So, the the largest values are [8,4], so the keys are [7,0].
>
> Is there any fast way to implement this algorithm?
> Any suggestions are welcome!
>
> Best regards,
> Davy

#get a list of tuples, with value in 1st position, key second
li = [(value,key) for key, value in dic.items()]

#sort the list
li.sort()

m = 2
#grab the m highest values, from the end of the list
li_high_keys = [k for v, k in li[-m:]]

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


Re: efficient data loading with Python, is that possible possible?

2007-12-12 Thread DouhetSukd
Back about 8 yrs ago, on pc hardware, I was reading twin 5 Mb files
and doing a 'fancy' diff between the 2, in about 60 seconds.  Granted,
your file is likely bigger, but so is modern hardware and 20 mins does
seem a bit high.

Can't talk about the rest of your code, but some parts of it may be
optimized

def parseValue(line, col):
s = line[col.start:col.end+1]
# no switch in python
if col.format == ColumnFormat.DATE:
return Format.parseDate(s)
if col.format == ColumnFormat.UNSIGNED:
return Format.parseUnsigned(s)

How about taking the big if clause out?  That would require making all
the formatters into functions, rather than in-lining some of them, but
it may clean things up.

#prebuilding a lookup of functions vs. expected formats...
#This is done once.
#Remember, you have to position this dict's computation _after_ all
the Format.parseXXX declarations.  Don't worry, Python _will_ complain
if you don't.

dict_format_func = {ColumnFormat.DATE:Format.parseDate,
ColumnFormat.UNSIGNED:Format.parseUnsigned,


def parseValue(line, col):
s = line[col.start:col.end+1]

#get applicable function, apply it to s
return dict_format_func[col.format](s)

Also...

 if col.format == ColumnFormat.STRING:
# and-or trick (no x ? y:z in python 2.4)
return not col.strip and s or rstrip(s)

Watch out!  'col.strip' here is not the result of stripping the
column, it is the strip _function_ itself, bound to the col object, so
it always be true.  I get caught by those things all the time :-(

I agree that taking out the dot.dot.dots would help, but I wouldn't
expect it to matter that much, unless it was in an incredibly tight
loop.

I might be that.

 if s.startswith('99') or s.startswith('00'): return -1

 would be better as...

#outside of loop, define a set of values for which you want to return
-1
set_return = set(['99','00'])

#lookup first 6 chars in your set
 def parseDate(s):
if s[0:6] in set_return:
   return -1
return int(mktime(strptime(s, "%y%m%d")))

Bottom line:  Python built-in data objects, such as dictionaries and
sets, are very much optimized.  Relying on them, rather than writing a
lot of ifs and doing weird data structure manipulations in Python
itself, is a good approach to try.  Try to build those objects outside
of your main processing loops.

Cheers

Douhet-did-suck

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


Re: psycopg2

2008-02-03 Thread DouhetSukd
On Feb 2, 9:22 pm, Tim Roberts <[EMAIL PROTECTED]> wrote:

> Also, psycopg will do the quoting for you.  You don't do it.  So this is
> what you want:

Second the above, it is much cleaner to leave the quoting to
psycopg2.  I know, I wrote my own quoting logic for dynamically
generated queries and I was happy as happy as a turkey on boxing day
to dump that code overboard when I realized I didn't need it anymore.

However, I think you are better off using dictionary based
substitutions:

cur.execute("SELECT * FROM names WHERE name= %(name)s ",
{"name":"S"} )

On small and simple queries it doesn't matter much and using dicts is
actually a bit harder.  On complex queries you may find:

- lots of binds.
- the same bind variable being used in several places
- optimization/adjustments may require you to rewrite the query
several times and shuffling the binds around into different
positions.

Maintaining positional binds is then a huge hassle compared to name-
based binds.

For the lazy, using dicts has another advantage:

name = "S"
firstname = "F"
cur.execute("SELECT * FROM names WHERE name = %(name)s and firstname =
%(firstname)s ", locals() )

Both MySQL and postgresql can work from the above examples as they
both accept name-binds and dicts.  Something which is not all that
clear in the docs.  Not all dbapi implementations allow this though.

Last but definitely not least, using dicts allows you to re-use bind
data more efficiently/painlessly:

di_cust = {"cust_id":
mynewcustid,"another_field_only_on_customer_table":3}

execute("insert into customer (cust_id) values (%
(cust_id)s...)",di_cust)

for order in get_order_lines():
  di_order = {"order_id":order.order_id}

  #grab shared field data from the customer dict.
another_field_only_on_customer_table will be ignored later.
  di_order.update(di_cust)

  execute("insert into customer_orders (cust_id,order_id) values (%
(cust_id)s, %(order_id)s...)",di_order)

None of this is very attractive if you believe in only using ORMs, but
it is bread and butter to looking after complex sql by yourself.

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


Re: Arrays/List, filters, Pytho, Ruby

2011-02-12 Thread DouhetSukd
On Feb 11, 1:24 pm, "LL.Snark"  wrote:
> Hi,
>
> I'm looking for a pythonic way to translate this short Ruby code :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=t.index {|x| x
> If you don't know Ruby, the second line means :
> What is the index, in array t, of the first element x such that x
> If can write it in python several ways :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=0
> while t[i]>=t[0] : i+=1
>
> ... not pythonic I think...
>
> Or :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=[j for j in range(len(t)) if t[j]
> ...too cryptic...
>
> I'm using Python 3.
>
> Thx

[i for i,v in enumerate(t) if v < t[0]][0:1]

empty list if no match.
-- 
http://mail.python.org/mailman/listinfo/python-list