Re: [Tutor] class methods: using class vars as args?

2010-05-23 Thread Matthew Wood
Hey Alex,

What's happening is that you're still in "defining functions" mode on the
line
def doSomething(self, arg3=self.arg1):

self, which is really nothing more than a parameter being passed in (special
parameter, but a parameter none the less) hasn't been assigned a value yet.


Imagine this function definition:

def do_something(a, b, c=a+b):

The parameter instances haven't been instantiated yet.


Another way to look at it:

You haven't finished defining the class yet, so you can't access data
specific to an instance.


Not the most technical description, but it's certainly how I look at it.

--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?


On Sun, May 23, 2010 at 1:40 PM, Alex Hall  wrote:

> Hello all,
> I know Python reasonably well, but I still run into basic questions
> which those over on the other python list request I post here instead.
> I figure this would be one of them:
> Why would this not work:
>
> class c(object):
>  def __init__(self, arg1, arg2):
>  self.arg1=arg1
>  self.arg2=arg2
>
>  def doSomething(self, arg3=self.arg1):
>  ...
>
> The above results in an error that "name 'self' is not defined". Why
> can I not set the default values of a method's arguments to class vars
> like that? Thanks!
>
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehg...@gmail.com; http://www.facebook.com/mehgcap
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] requesting a help

2010-05-23 Thread Matthew Wood
I'd start with something like this:

final_result = []
for data, target in zip(f, t):
a, b = [elem.strip() for elem in line.split()]
c = target.strip()
final_result.append([[a, b], [c]])

Though I'm not sure why you have the "result" data in single element lists.
--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?


On Sun, May 23, 2010 at 10:34 PM, Ahmed AL-Masri wrote:

>
> I am facing the same problem that little complicated.
> I have this kind of data in a file and actually it's coming from another
> class and it's in form
> ex:
> 0 0
> 0 1
> 1 0
> 1 1
> and another data which it's in form :
> 0
> 1
> 1
> 0
> so now what I need to put it in form
> data= [[[0,0],[0]],
>   [[0,1],[1]],
>   [[1,0],[1]],
>   [[1,1],[0]]
>  ]
>
> that is the form for a class that I can use the [0,1] is the inputs and
> inputs[0] is = 0 and inputs[1] is = to 1 . the same thing to the output[0]
> is = 0 and so on
> ok, now this is the problem
> I have successes to to that reading from file in form
> 0 0
> 0 1
> 1 0
> 1 1
> the output
> 0
> 1
> 1
> 0
> and I write it in a file called it data in the new form which is exactly
> what I want in form
>  [[[0,0],[0]],
>   [[0,1],[1]],
>   [[1,0],[1]],
>   [[1,1],[0]],]
> but I got a problem. I cannot use this as a data when I read it from the
> data file cuz it's string and I tried to use int but couldn`t solve it yet.
> wish you can help me to find the solution in this problem
> ether I can read the data from the original file and deal with
> it separately or write it to file and read it again which I am trying to do
>
> f=open('data.txt')
> t=open('target.txt')
> n=file('newdata.txt','w')
>
> def arange (inputs, targets, outputfile):
>   casesNo = len (inputs.readline())
>
>   for s in range (casesNo):
> for line in inputs:
> data=line.rsplit()
> i=','.join(data)
> break
> for line1 in targets:
> data1=line1.rsplit()
> #print data1[0]
> u=','.join(data1)
> z= str(i)
> w= str(u)
> outputfile.write('[[%s],' % (z)+ '[%s]], \n' %(w))
> break
> outputfile.close()
>
> arange(f,t,n) # f : input data, t: target data, n: outputfile
> looking to hearing from you as soon as,
> once again thanks for your help and cooperation,
>
> Regards,
>
>
>
> --
> Hotmail: Trusted email with Microsoft’s powerful SPAM protection. Sign up
> now. 
>
> --
> Hotmail: Powerful Free email with security by Microsoft. Get it 
> now.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PYTHON 3.1

2010-05-24 Thread Matthew Wood
Well, I'd use the raw_input function instead of the input function.

and I'd check out the math.floor function as well.  :-)

Lemme know if you have any other questions.

--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?


On Mon, May 24, 2010 at 1:55 AM, Dipo Elegbede wrote:

> Hello Sir,
>
> I'm trying to write a program that checks for the square root of any
> number input by the User.
> It's a fairly simple coding though atleast for an ambitious beginner.
>
> I want the code to first, calculate the square root and the tell the
> user whether or not.
>
> It should end up telling the User that this is a perfect square.
>
> Below is the coding:
>
> print('Check for a perfect square')
> number = int(input('Which number are you checking for? '))
> square = (number)**(1/2.0)
> print('Square Root is = %.2f'%(square))
>
> I am trying to put in something like:
>
> if square (is perfect square):
> print ('This is a perfect square')
>
> Pls Help.
>
> Thanks.
>
>
> On 5/21/10, ALAN GAULD  wrote:
> > I suspect the likely cause is that you need to change directory to the
> > directory(folder) where your code lives. Lets say you keep your code
> > in C:\Projects\Python
> >
> > start the DOS box
> > Type (the bits in bold):
> >
> > C\:..\> cd C:\Projects\Python
> >
> > Now type
> >
> > C:\Projects\Python>python myprogram.py
> >
> > using whatever your python file is called...
> >
> > Now, provided everything is set up properly it should run.
> > In fact you might even get away wioth jusdt typing:
> >
> > C:\Projects\Python\> myprogram.py
> >
> > Because in theory Windows should know to run python
> > for a .py file But it often "forgets" :-(
> >
> >
> >  Alan Gauld
> > Author of the Learn To Program website
> > http://www.alan-g.me.uk/
> >
> >
> >
> >
> >
> > 
> > From: Dipo Elegbede 
> > To: ALAN GAULD 
> > Sent: Friday, 21 May, 2010 19:35:57
> > Subject: Re: PYTHON 3.1
> >
> > I still can not successfully run Python from the windows command
> > prompt after doing all you've directed in the tutorials. (Pls note,
> > I'm not ruling out the probability that I didn't get the instructions
> > right. As a matter of fact, this is possibly why I still have the
> > problem.)
> > Sir, I'm hoping you could take me through that again.
> > Like when I type
> > C:document and setting>python xx.py
> > It tells me the file does not exit.
> > It atimes starts python when I type python at the prompt to give:
> > C:Python>
> > When i type the name of the file at the python prompt, I still get an
> > error.e.g
> > Python>read.py
> > It comes with error.
> > It's challenging because some examples in your tutorial require I run
> > from the prompt and so I'm getting stucked midway.
> > Please Help.
> > Regards,
> >
> > On 5/21/10, Dipo Elegbede  wrote:
> >> Hi Alan Sir,
> >>
> >> I have been reading through your site and the tutorials, it's just
> >> something else, I started feeling like a real programmer when i worked
> >> through the easygui thingy, it was really a mind-blower.
> >> I hope you'll pardon my pace of learning. I still didn't get some
> >> aspect under 'Conversing with the user'
> >> i really read through and I am hoping to reread but I would like you
> >> shed more light on the stdin and stdout areas.
> >> They are really confusing.
> >> Please help.
> >> Regards,
> >>
> >> On 5/20/10, Dipo Elegbede  wrote:
> >>> Ok, Master. I should would have a lot to learn from you.
> >>>
> >>> I hope you'd oblige me that rare priviledge.
> >>>
> >>> Regards, Master!
> >>>
> >>> On 5/20/10, ALAN GAULD  wrote:
> 
> 
> > I may consider pascal after excelling in Python.
> 
>  I wouldn't bother, the only place it is used nowadays is in the
>  Borland Delphi programming tool for Windows(*). Delphi is very
>  good if you already know Pascal but otherwise is just another
>  language to learn! :-)
> 
>  (*)Although there is a freeware version of Pascal - fpc - that is
>  compatible with Delphi if you really want to try it out. But
>  definitely wait till after Python. (Actually Python is a good
>  intro to Delphi, they have many features in common)
> 
>  Alan G.
> >>>
> >>>
> >>> --
> >>> Elegbede Muhammed Oladipupo
> >>> OCA
> >>> +2348077682428
> >>> +2347042171716
> >>> www.dudupay.com
> >>> Mobile Banking Solutions | Transaction Processing | Enterprise
> >>> Application Development
> >>>
> >>
> >>
> >> --
> >> Elegbede Muhammed Oladipupo
> >> OCA
> >> +2348077682428
> >> +2347042171716
> >> www.dudupay.com
> >> Mobile Banking Solutions | Transaction Processing | Enterprise
> >> Application Development
> >>
> >
> > --
> > Sent from my mobile device
> >
> > Elegbede Muhammed Oladipupo
> > OCA
> > +2348077682428
> > +2347042171716
> > www.dudupay.com
> > Mobile Banking Solutions | Transaction Processing | Enterprise
> > Application Development
> >
>
>
> --
> Elegbede Muhammed Oladipupo
> OCA
> +2348077682428
> +2347042171716

Re: [Tutor] PYTHON 3.1

2010-05-24 Thread Matthew Wood
Well, what do you know!

Turns out, I never use that function anyway, so it won't change a damn thing
for me.  But thanks for the heads up!


And thanks for the nod to the haiku.  So many people don't see it.

--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?


On Mon, May 24, 2010 at 3:36 AM, C M Caine  wrote:

> On 24 May 2010 09:20, Matthew Wood  wrote:
> > Well, I'd use the raw_input function instead of the input function.
> >
> > and I'd check out the math.floor function as well.  :-)
> >
> > Lemme know if you have any other questions.
> >
> > --
> >
> > I enjoy haiku
> > but sometimes they don't make sense;
> > refrigerator?
>
> raw_input has been renamed to input in python 3.0. To get the old
> input behaviour you have to use eval.
>
> Great sig, btw.
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] circular looping

2010-05-24 Thread Matthew Wood
This is a GREAT application for generators!

def cycle(seq, index):
l = len(seq)
for i in range(len(seq)):
cursor = (i + index) % l
yield seq[cursor]

Then you just pass it the starting index you want, and all is well in the
world.  :-)

Also, gratuitous use of the enumerate function in for-loops is grand:

for x_index, x in enumerate(myres):
if not x in DON:
continue
for y_index, y in enumerate(cycle(myres)):
print x, y
if y in ALL:
a[x_index][y_index] = 1

print '-'


--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?


On Mon, May 24, 2010 at 10:35 AM, Bala subramanian <
bala.biophys...@gmail.com> wrote:

> Friends,
> I have a list. I have to do some comparison of each item in the list with
> each other items in the list.
>
> from numpy import zeros
> a=zeros((5,5))
>
> myres=['R', 'N', 'L', 'C', 'M']
> DON=['R','N','L'] ; ALL=['R','L','M','S']
>
> for x in myres:
> for y in myres:
> if x in DON:
>   if y in ALL: a[res.index(x),res.index(y)] = 1
>  else: continue
>
> But here the value of y changes sequentially. I want y to cycle through the
> list something like the following. Is there any function to do such circular
> iteration.
> cycle 1 y's value should be 'N', 'L', 'C', 'M, 'R'  index 1,2,3,4,0 of
> myres
> cycle 2 y's value should be 'L', 'C', 'M, 'R', 'N'  index 2,3,4,0,1
> ,,
> cycle 3 y's value should be  'C', 'M', 'R', 'N','L' index 3,4,0,1,2
> ,,
>
> Thank you,
> Bala
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-27 Thread Matthew Wood
#!/usr/bin/env python


Here's my best attempt.  I'm not sure if it's "simpler" than yours,
but for me it seems a bit cleaner.  Then again, I LOVE the zip
operator, and the '*' operator too.  :-)  Whenever I see a "transpose
this" type problem, I think zip.


y = {'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}

print y

old = [dict([(i, y[i][j]) for i in y.keys()])
  for j in range(len(y[y.keys()[0]]))]
print old


keys, values = zip(* y.items())
new = [dict([(i, j) for i, j in zip(keys, column)])
    for column in zip(* values)]

print new

print new == old

I BELIEVE there's some new cool features in 2.6 or maybe 3.0 where
non-simultaneous access to my_dict.keys() and my_dict.values() will
keep them "paired up", but I don't know the details.  If you skipped
the upper line (setting keys and values) you'd be accessing y.keys() 3
times (in this example).  I'm not sure if you're guaranteed to have
the order remain the same for all three accesses.  If that's the case,
I'd change the code to be:

# This line isn't necessary #keys, values = zip(* y.items())
new = [dict([(i, j) for i, j in zip(y.keys(), column)])
for column in zip(* y.values())]

or even

# This line isn't necessary #keys, values = zip(* y.items())
new = [dict([(i, j) for i, j in zip(y, column)])
for column in zip(* y.values())]


But since I'm a coward, and I'd like my code to run on older versions
of python too, I'd leave the initial step.
--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?


On Thu, May 27, 2010 at 4:15 PM, David Perlman  wrote:
>
> Using the csv.DictReader and csv.DictWriter lets you read and write lists of 
> dictionaries from files containing tabular data.  I have a system that 
> naturally generates tabular data in the form of a dictionary of lists: the 
> dictionary key is the name of the column, and then the value is a list which 
> contains the data for that column.  Sort of like a spreadsheet.  I would like 
> to use csv.DictWriter to write out this data but that requires a list of 
> dicts.
>
> I can convert the dict of lists to a list of dicts, and thus make it 
> compatible with csv.DictWriter, with the following ugly comprehensions:
>
> >>> y
> {'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}
> >>> [dict([(i,y[i][j]) for i in y.keys()]) for j in 
> >>> range(len(y[y.keys()[0]]))]
> [{'a': 1, 'c': 7, 'b': 4}, {'a': 2, 'c': 8, 'b': 5}, {'a': 3, 'c': 9, 'b': 6}]
>
> ...but I'm wondering if anyone knows of a more elegant way, perhaps something 
> built-in suited for this purpose...
>
> I am aware that any solution will only work if the lists in the dict are all 
> the same length.  :)
>
> Thanks!
>
>
> --
> -dave
> "Pseudo-colored pictures of a person's brain lighting up are
> undoubtedly more persuasive than a pattern of squiggles produced by a
> polygraph.  That could be a big problem if the goal is to get to the
> truth."  -Dr. Steven Hyman, Harvard
>
>
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-27 Thread Matthew Wood
Well, that makes a lot of sense.  I probably should have looked it up.  :-)

That said, the version with an extra line will work on python < 2.6,
so I'd probably just leave it that way.


But thanks the docs pointer.  Always useful.


That said, if I KNEW that my software was only to be implemented in
3.0 or greater, I'd go with the new, cool, slick,
shows-I-read-the-docs way!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Speed it up...

2010-05-27 Thread Matthew Wood
On Thu, May 27, 2010 at 3:37 AM, trias  wrote:
>
> Hi,
>
>  I have wrote the following lines that work fine, but are quite slow, are
> there any obvious things I can consider to speed things up?
>
>  Thanks
>
> import MySQLdb
>
> import scipy
>
> import csv
>
> dbtest=MySQLdb.connect(host="***",user="***",passwd="***")
>
> cursor=dbtest.cursor()
>
> cursor.execute("""SELECT tfs_name FROM tfs_sites GROUP by tfs_name""")
>
> result=cursor.fetchall()
>
> dbtest.close()
>
> TFname=[]
>
> for row in result:
>
>    TFname.append(row[0])
>
> del result
>
> T={}
>
> i=0
>
> for TF in TFname:
>
>    while i<1:
>
>        dbtest=MySQLdb.connect(host="***",user="***",passwd="***",db="***")
>
>        cursor=dbtest.cursor()
>
>        cursor.execute("""SELECT tfs_chr,tfs_pos,tfs_val FROM tfs_sites
> WHERE tfs_name='%s'"""%(TF))
>
>        result=cursor.fetchall()
>
>        TFchr=[]
>
>        TFpos=[]
>
>        TFval=[]
>
>        i+=1
>
>        for row in result:
>
>            TFchr.append(row[0])
>
>            TFpos.append(row[1])
>
>            TFval.append(row[2])
>
>            TFc=[[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
>
>            counter=0
>
>            for TFsite in TFchr:
>
>
> TFc[(int(TFsite)-1)].append((int(TFpos[counter]),int(TFval[counter])))
>
>                T[TF]=TFc
>
>                counter+=1
> --
> View this message in context: 
> http://old.nabble.com/Speed-it-up...-tp28691677p28691677.html
> Sent from the Python - tutor mailing list archive at Nabble.com.
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


Heh, I guess I'll try the "replay after message" plan everyone seems
to like here.


You don't need to make a new connection or cursor every time you run a query.
Just use the cursor you created once.


Secondly, if you can figure out a way to combine all your queries into
one larger query, your speed will increase.  In this case, you're
querying the same table multiple times.  It'd be easier on your
database if you just queried it once.

SELECT tfs_name, tfs_chr, tfs_pos, tfs_val FROM tfs_sites

You'll still get all the information you'd get the other way, and you
only have to hit the DB once.  (This somewhat invalidates the first
point I made, but ...)


If you can't reduce it to that single query (for whatever reason),
since your first query is only grabbing a single column of data, you
should use "distinct" instead of "group by".

SELECT DISTINCT tfs_name FROM tfs_sites




Also, and this will be a FAR SMALLER speedup:

you have several instances where you do this:

big_container = []
for row in some_query_result:
big_container.append(row[0])

it's faster, and I think clearer/cleaner to do:

big_container = [row[0] for row in some_query_result]

or, if you want to make sure they're all ints:

big_container = [int(row[0]) for row in some_query_result]


TFname, TFchr, TFpos, TFval can all be constructed this way.



There's a few other things you could do that would speed up things,
but the biggest would be to reduce the connection time to your DB, and
reduce the number of queries.



--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-27 Thread Matthew Wood
Wow.  Something horrible happened here.

http://xkcd.com/386/


I THOUGHT the guaranteed same-ordering of dict.keys and dict.values started
in python 2.6.  That was a simple mistake.

It turns out, that's not the case.  But in general, access to dicts and sets
is unordered, so you can't/don't/shouldn't count on ordering.  The solution
to take keys and values from dict.items() DOES guarantee their ordering,
even if dict.keys and dict.values aren't.

That's all I was trying to say.  It's unfortunate that I had the python
version  the guaranteed same-ordering wrong.


I'm certainly not trying to say that you shouldn't trust language features.
 That's not it at all.

But imagine if that guaranteed behavior started in 2.5 for example.  Then,
if you want your code to work on 2.3, you'd definitely want to pull them out
of the dict via dict.items().



I think your response was quite rude.  I mean really, cargo cult
programming?  May John Frum forgive your unnecessary aggression.  I just
tried to suggest a solution and I think it's crappy that you accused me of
"programming without understanding what you are doing".

I recognize that you told me not to take offense; but, no offense, nobody
cared when Carrie Prejean (Miss California) said that either.



So, I do apologize for the mistake I made, and hopefully we (both you AND I)
can nip this mailing-list flame-war in the bud.



Anyway, I hope David (the original questioner) got a little help, or at
least another token for confirmation that any list comprehension solution
will be semi-ugly/semi-complex.


--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-29 Thread Matthew Wood
On Fri, May 28, 2010 at 6:55 PM, Steven D'Aprano wrote:

> On Fri, 28 May 2010 12:00:46 pm Matthew Wood wrote:
>
> > I THOUGHT the guaranteed same-ordering of dict.keys and dict.values
> > started in python 2.6.  That was a simple mistake.
> >
> > It turns out, that's not the case.  But in general, access to dicts
> > and sets is unordered, so you can't/don't/shouldn't count on
> > ordering.
>
> You can't count on getting a *specific* order, but you can count on
> getting a *consistent* order. (So long as you don't modify the
> dictionary between calls, of course.)
>
>
> > The solution to take keys and values from dict.items()
> > DOES guarantee their ordering, even if dict.keys and dict.values
> > aren't.
>
> And so does zip(d.keys(), d.values()). They both guarantee the same
> consistent ordering.
>
> The fact is, yes, your solution does work, but your rationale for
> preferring it is irrational. That's not meant to be insulting, we all
> have preferences based on irrational little quirks, we wouldn't be
> human otherwise. When there are two equally good solutions, you have to
> pick one or the other for essentially an irrational reason -- if there
> was a rational reason to prefer one over the other, they wouldn't be
> equally good.
>
> If you choose to continue using the dict.items() solution, by all means
> do so because you like it, or because it gives you a warm fuzzy
> feeling, or because it's easier for you to remember. Or because you've
> profiled it and it is 3% faster or uses 1% less memory (I made those
> numbers up, by the way). These are all good reasons for choosing a
> solution over another solution.
>
> But stop trying to justify it on the basis of it being safer and more
> backwards compatible, because that's simply not correct. That's what
> pushes your solution out of personal preference to cargo-cult
> programming: following the form without understanding the semantics.
> The semantics of dict.keys() and values() guarantee the same order.
>
>
> [...]
> > But imagine if that guaranteed behavior started in 2.5 for example.
> > Then, if you want your code to work on 2.3, you'd definitely want to
> > pull them out of the dict via dict.items().
>
> But it didn't start in 2.5. It has been part of Python essentially
> forever. If I argued, "Imagine that dictionaries only gained an items()
> method in 2.5, and you wanted it to work in 2.3, you'd need to avoid
> dict.items()", what would you say?
>
>
> > I think your response was quite rude.
>
> If you can't take constructive criticism without getting offended and
> crying "oh how rude!", there's a serious problem.
>
>
> > I mean really, cargo cult programming?
> > I just tried to suggest a solution and I think it's crappy that you
> > accused me of "programming without understanding what you are doing".
>
> I think it is quite clear that in *this* specific case you don't
> understand what you are doing, because you are recommending a solution
> that you labelled "This line isn't necessary". If it's not necessary,
> why include it?
>
> We all code badly at times. I'm sure if you were to go through my code
> line by line, you'd find some real clangers caused by me failing to
> fully understand what I was doing too. Patches and bug reports are
> welcome :)
>
> If it makes you feel any better, I was once told by Alex Martelli (one
> of the Python demi-gods) that if he were marking my code for an
> assignment he would fail me over what I believed was a trivial
> stylistic difference of opinion. I was declaring globals even if I
> didn't assign to them, e.g.:
>
> def func(x):
>global y
>return x + y
>
> It took me a long time, perhaps a few years, but I've come around to
> Martelli's position on globals and no longer declare them unless I
> assign to them. I still think a fail over such a small issue is awfully
> harsh, but perhaps he was having a bad day. I've come to understand the
> semantics of the global statement better, and can see that unnecessary
> global declarations goes against the purpose and meaning of the
> statement. I was, in short, cargo-cult programming, using global
> without understanding it. As harsh as Martelli's response was, I
> believe I'm a better coder today because of it than if he had just
> patted me on the head and said "that's okay, you write anything you
> like".
>
>
>
> --
> Steven D'Aprano
> ___

Re: [Tutor] namespaces

2010-05-30 Thread Matthew Wood
That's probably my least favorite error message in python.  I wish that
somehow it would have the line number of the first assignment statement
instead of the first read statement.  I know why it's not that way, but I
just wish it weren't.

--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?


On Sun, May 30, 2010 at 10:47 AM, Robert Johansson <
robert.johans...@math.umu.se> wrote:

> Thanks Evert for pointing out the difference and the discussion on global
> variables, it helped.
>
> /Robert
>
> -Ursprungligt meddelande-
> Från: Evert Rol [mailto:evert@gmail.com]
> Skickat: den 30 maj 2010 18:34
> Till: Robert Johansson
> Kopia: tutor@python.org
> Ämne: Re: [Tutor] namespaces
>
>  Hi Robert
>
> > This code generates the message "UnboundLocalError: local variable
> 'doubles' referenced before assignment" (line: if d[0] == d[1] and doubles
> == 2:)
> >
> > http://pastebin.com/mYBaCfj1
> >
> > I think I have a fair picture of what it means but I would be very happy
> if someone could explain the difference between the two variables h and
> doubles in the code. Why is one accessible from the function but not the
> other? I looked into rules for namespaces but I'm still confused. Below is
> another sample of the code
>
> You assign a value to doubles in the roll() function, making Python think
> doubles is a local variable (which hasn't been assigned anything when you
> first use it, throwing the exception).
> If you assign some value to h after the first line in roll() (eg, h = 6),
> you'd get the same exception, but then for h.
> So, if you assign a value to a variable inside a function() and you want
> that variable to be the global one (instead of the implicitly assumed local
> one), you'll have to explicitly tell Python that: "global doubles" (probably
> on the first line in the function).
> Since you hadn't assigned any value to h inside roll(), only used it,
> Python assumes it's the global one.
>
> See also the second answer to this question:
> http://stackoverflow.com/questions/423379/global-variables-in-python
>
> Hope that helps,
>
>  Evert
>
>
> >
> > Cheers, Robert
> >
> > from random import *
> >
> > h = 6
> > doubles = 0 # current number of consecutive doubles
> >
> > def roll():
> > d = [randint(1, h), randint(1, h)]
> > if d[0] == d[1] and doubles == 2:
> > doubles = 0
> > return 0
> > elif d[0] == d[1] and doubles < 2:
> > doubles += 1
> > return sum(d)
> > else:
> > return sum(d)
> >
> > for n in range(10):
> > d = roll()
> > print d
> >
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] treeTraversal, nested return?

2010-06-04 Thread Matthew Wood
In general, there's 2 solutions to your "unflattening" problem.

A) The general solution: Keep track of the depth you're at, and add
tabs/spaces ('\t' * depth) as necessary.

B) The xml solution: Use (for example) the dom.minidom module, and create a
new "ul node" and populate it with children, at each level.  Then, have the
xml do the printing for you.


For what it's worth, I may have a slight nit-pick of your final output.  I
don't believe you can technically have a  child of a  node.  I'm not
absolutely sure on that, but my quick google searching has appeared to
confirm.  If that turns out to be true, you'll need to change the structure
of your output.



1,0,data

555,1,image
...




All of that is, of course, null and void if you define your own xml scheme.





--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?


On Fri, Jun 4, 2010 at 11:15 AM,  wrote:

> All,
>
> any observations might be helpful. For the display of database contents I
> have the following problem:
>
> Database querys will return data to me in tuples of the following sort:
> each tuple has a unique id, a parent id, and a type.
>
> a parent id of 0 indicates that the element has no parent.
> not all data elements have children
> image elements have no children and must have a parent
>
> So the contents of the db is a tree of sorts:
>
> (1, 0, work)
> (555, 1, image)
> (556, 1, work)
> (557, 556, image)
> (558, 556, work)
> (559, 558, image)
> (560, 558, work)
> (561, 556, image)
> (562, 556, image)
> (563, 1, work)
> (564, 563, work)
> (565, 1, work)
>
> I have a function that will traverse this tree, summoning lists of tuples
> at each leaf. Well and good; it took a lot of trial and error, but it was a
> fine education in tree traversal.
>
> def makeHeirarchy(id):
>id = parentPath(id)[-1]
>rootimages = getImages(id[0])
>rootworks = getWorks(id[0])
>heirarchy = treeTraversal(rootworks, [id, rootimages])
>return heirarchy
>
> ## which calls this recursive function:
>
> def treeTraversal(listIn,result):
>for x in listIn:
>if not getWorks(x[0]):
>result.append(x)
>result.append(getImages(x[0]))
>else:
>result.append(x)
>result.append(getImages(x[0]))
>treeTraversal(getWorks(x[0]), result)
>return result
>
> My problem is that this returns the tuples to me in a flat list.
> I've been trying to work out how I can get it to return some sort of nested
> structure: nested lists, dictionaries, or html thus:
>
> 
> 1,0,data
>
>555, 1, image
>556, 1, data
>
>557, 556, image
>561, 556, image
>562, 556, image
>558, 556, data
>
>559, 558, image
>560, 558, image
>
>
>563, 1, data
>
>564, 563, data
>
>565, 1, data
>
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] treeTraversal, nested return?

2010-06-05 Thread Matthew Wood
On Fri, Jun 4, 2010 at 7:40 PM,  wrote:

> Matthew,
>
> sorry for responding to you instead of the list
>
>
> Thanks for trying to tutor the dunderheaded. It is exactly the general
> solution I wish to learn. But how, in the context of my treeTraversal
> function, does one "keep track of the depth you're at"? Tabs are all very
> well, but what I want is truly a nested structure, and as you point out in
>  that's not what I was showing in my html (though deprecated,
> browsers still render lists like the one I showed).
>
> The simplest and most graphic example would be a nested list of lists, but
> for the life of me I can't work out how to generate that in this context.
>
> Jon
>
>
>
> On Fri, 4 Jun 2010, Matthew Wood wrote:
>
>  In general, there's 2 solutions to your "unflattening" problem.
>> A) The general solution: Keep track of the depth you're at, and add
>>
> tabs/spaces ('\t' * depth) as necessary.
>
>
>
>

Spir's example demonstrates the idiom.  Watch the "level" variable.  During
our function, it gets incremented, and then passed into the next recursive
call.  Thus, each call to the recursive function is passing along the
appropriate tab depth level.

Good luck yo.  Recursion is one of those concepts that just clicks one day.
 At least that's how it is for me.

I'll attempt to provide a pseudo pseudo code description:



def recursive_func(data, indent_level):

if is_printable_node(data):
print '\t' * indent_level + string_format(data)

else:
# now we know it's not a node, so it must be a child list.
for sub_data in data:
recursive_func(sub_data, indent_level + 1)


Again, watch the indent_level variable.


--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regular expression grouping insert thingy

2010-06-08 Thread Matthew Wood
re.sub(r'(\d+)x', r'\1*x', input_text)

--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?


On Tue, Jun 8, 2010 at 10:11 PM, Lang Hurst  wrote:

> This is so trivial (or should be), but I can't figure it out.
>
> I'm trying to do what in vim is
>
> :s/\([0-9]\)x/\1*x/
>
> That is, "find a number followed by an x and put a "*" in between the
> number and the x"
>
> So, if the string is "6443x - 3", I'll get back "6443*x - 3"
>
> I won't write down all the things I've tried, but suffice it to say,
> nothing has done it.  I just found myself figuring out how to call sed and
> realized that this should be a one-liner in python too.  Any ideas?  I've
> read a lot of documentation, but I just can't figure it out.  Thanks.
>
> --
> There are no stupid questions, just stupid people.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: treeTraversal, nested return?

2010-06-09 Thread Matthew Wood
Gah, hit the reply button instead of reply-all.  :-(

--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?


-- Forwarded message --
From: Matthew Wood 
Date: Wed, Jun 9, 2010 at 2:30 PM
Subject: Re: [Tutor] treeTraversal, nested return?
To: jjcr...@uw.edu


Well, I've taken a look at your code.  In your last example, the appending
last line here:

> else:
>for x in getWorks(id):
>   result.extend(makeNestedLists(x[1]))

uses, a list.extend call.  If you switch that to append, you SHOULD see the
result you're looking for.  ...at least as best I can guess without
replicating the code and having some good test cases.


Here's some of your other questions:

>To my surprise, I say, because it looks like it shouldn't work at all
>with the result being set to the empty list with each recursion;

Each time you call the function 'makeNestedLists' a new copy of all the
local variables is created.  Thus, you aren't blanking the 'result' list
each time; instead you're creating a new list each time.  Then, when you
return the list, you then shove it into the parent-function-instance list.

Just take care to understand the difference between:

[1, 2, 3].append([4, 5, 6])  -> [1, 2, 3, [4, 5, 6]]
[1, 2, 3].extend([4, 5, 6]) -> [1, 2, 3, 4, 5, 6]

Your list comprehension example above adds an extra list wrapper around
things, which is why the extend worked.



--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?


On Wed, Jun 9, 2010 at 12:40 PM,  wrote:

> Thanks to Matthew and Denis for trying to enlighten me. Thanks to your
> clues I've made some progress; however, I can't seem to get the hang of the
> usual recursion trick of keeping track of the level one is on. It doesn't
> work, I suppose, because the data structure I'm traversing isn't actually
> nested, its a flat series of lists of tuples.
>
> I did finally get a function to traverse the "tree-like" data coming from
> the db
>
> getRecord() returns a tuple of record-type, record-id, parent-id, and
> title, thus:
> ('work', 47302, 47301, 'record title')
>
> getImages(id) returns a list of 'image' tuples whose parent-id is id
> getWorks(id) returns a list of 'work' tuples whose parent-id is id
>
> works can be nodes, images can't
>
> so:
>
>   def makeDecendentList(id, result):
>  result.append(getRecord(id))
>  if getImages(id):
> for x in getImages(id):
>result.append(x)
>  if not getWorks(id):
> return
>  else:
> for y in getWorks(id):
>makeDecendentList(y[1],result)
>  return result
>
> called with the empty list as the second argument.
>
> Well and good. This walks the 'tree' (following the parent-ids) and returns
> me a list of all the decendents of id. But what I wanted was a nested data
> structure.
>
> In the fashion of an ape given a typewriter and sufficient time, I trial
> and errored my way to this:
>
>   def makeNestedLists(id):
>  result = []
>  result.append(getRecord(id))
>  result.extend(getImages(id))
>  if not getWorks(id):
> return result
>  else:
> result.extend([makeNestedLists(x[1]) for x in getWorks(id)])
>  return result
>
> To my surprise, this gets me exactly what I wanted, eg:
>
>   [  ('work', 47301, 47254, 'a title'),
>  ('image', 36871, 47301, 'a title'),
>  ('image', 36872, 47301, 'a title'),
>  [  ('work', 47302, 47301, 'a title'),
> ('image', 10706, 47302, 'a title'),
> ('image', 10725, 47302, 'a title')
>  ]
>   ]
>
> To my surprise, I say, because it looks like it shouldn't work at all with
> the result being set to the empty list with each recursion; moreover, if I
> spell out the loop in the list comp like this:
>
>   def makeNestedLists(id):
>  result = []
>  result.append(getRecord(id))
>  result.extend(getImages(id))
>  if not getWorks(id):
> return result
>  else:
> for x in getWorks(id):
>result.extend(makeNestedLists(x[1]))
>  return result
>
> I once again get a flat list of all the decendents of id.
>
> I know it's sad, but can any wise tutor explain to me what's going on in
> the code that I myself wrote?
>
> Thanks,
> Jon
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor