Re: [Tutor] Another assert() question

2008-07-12 Thread Martin Walsh
Dick Moores wrote:
> At 07:39 PM 7/12/2008, Kent Johnson wrote:
>> On Sat, Jul 12, 2008 at 6:03 PM, Dick Moores <[EMAIL PROTECTED]> wrote:
>> > At 01:34 PM 7/12/2008, Kent Johnson wrote:
>>
>> >> In [2]: assert(False, "Asserted false")
>> >>
>> >> This is "assert condition" where the condition is a tuple with two
>> >> elements, hence true so there is no output.
>> >
>> > In [13]: assert(3 < 2 , "qwerty")
>> >
>> > In [14]:
>> >
>> > I don't understand that logic. Could you unpack it for me?
>>
>> (False, "Asserted false") is a tuple containing two values, False and
>> "Asserted false".
>>
>> "assert x" evaluates x as a boolean; if it evaluates to False, the
>> assertion is raised. A tuple with two elements will always evaluate to
>> True so the assertion is never raised.
> 
> But why will a tuple with two elements will always evaluate to
> True?
> 
> In [2]: (3,5) == True
> Out[2]: False
> In [3]: ("qwerty", "asdfg") == True
> Out[3]: False
> In [4]:

You might find it easier to think about this way:

In [1]: bool((3, 5))
Out[1]: True

In [2]: bool(("qwerty", "asdfg"))
Out[2]: True

More info here:
http://docs.python.org/lib/truth.html
http://docs.python.org/lib/node34.html

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


Re: [Tutor] Another assert() question

2008-07-12 Thread Marc Tompkins
On Sat, Jul 12, 2008 at 8:10 PM, Dick Moores <[EMAIL PROTECTED]> wrote:

> But why will a tuple with two elements will always evaluate to
> True?
>
> In [2]: (3,5) == True
> Out[2]: False
> In [3]: ("qwerty", "asdfg") == True
> Out[3]: False
> In [4]:
>
>
The value formally known as True is only one member of the set of things
that don't evaluate to False...  Confused yet?

Anyway, this might make it a bit clearer:

>>> (3,2) == True
False
>>> if (3,2): print "Tru, dat"
...
Tru, dat
>>>

In other words, "(3,2)" isn't exactly the same as "True" - but it doesn't
evaluate to False, either, so it's true.

It's a bit like arguments about the nature of Good and Evil, I'd say.
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Another assert() question

2008-07-12 Thread Dick Moores

At 07:39 PM 7/12/2008, Kent Johnson wrote:

On Sat, Jul 12, 2008 at 6:03 PM, Dick Moores <[EMAIL PROTECTED]> wrote:
> At 01:34 PM 7/12/2008, Kent Johnson wrote:

>> In [2]: assert(False, "Asserted false")
>>
>> This is "assert condition" where the condition is a tuple with two
>> elements, hence true so there is no output.
>
> In [13]: assert(3 < 2 , "qwerty")
>
> In [14]:
>
> I don't understand that logic. Could you unpack it for me?

(False, "Asserted false") is a tuple containing two values, False and
"Asserted false".

"assert x" evaluates x as a boolean; if it evaluates to False, the
assertion is raised. A tuple with two elements will always evaluate to
True so the assertion is never raised.


But why will a tuple with two elements will always evaluate to
True?

In [2]: (3,5) == True
Out[2]: False
In [3]: ("qwerty", "asdfg") == True
Out[3]: False
In [4]:

Dick


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


Re: [Tutor] Another assert() question

2008-07-12 Thread Kent Johnson
On Sat, Jul 12, 2008 at 6:03 PM, Dick Moores <[EMAIL PROTECTED]> wrote:
> At 01:34 PM 7/12/2008, Kent Johnson wrote:

>> In [2]: assert(False, "Asserted false")
>>
>> This is "assert condition" where the condition is a tuple with two
>> elements, hence true so there is no output.
>
> In [13]: assert(3 < 2 , "qwerty")
>
> In [14]:
>
> I don't understand that logic. Could you unpack it for me?

(False, "Asserted false") is a tuple containing two values, False and
"Asserted false".

"assert x" evaluates x as a boolean; if it evaluates to False, the
assertion is raised. A tuple with two elements will always evaluate to
True so the assertion is never raised.

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


Re: [Tutor] Another assert() question

2008-07-12 Thread Dick Moores

At 01:34 PM 7/12/2008, Kent Johnson wrote:

On Sat, Jul 12, 2008 at 4:01 PM, Dick Moores <[EMAIL PROTECTED]> wrote:
> _Python in a NutShell_, p. 138 has a bit on the assert statement which I
> don't completely understand.
>
> It says the syntax is
>
> assert condition[, expression]
>
> I was hoping to put some sort of explanation of failure in an assert
> statement. But how to do it?
>
> In my code I have
>
> assert(len(list(set(colors_used_this_cycle))) ==
> len(colors_used_this_cycle), "A color has been used twice!")

Leave out the outermost parentheses, assert is a statement, not a 
function call.


Ah. OK.


In [2]: assert(False, "Asserted false")

This is "assert condition" where the condition is a tuple with two
elements, hence true so there is no output.


In [13]: assert(3 < 2 , "qwerty")

In [14]:

I don't understand that logic. Could you unpack it for me?



In [3]: assert False, "Asserted false"
---
Traceback (most recent call last)

/Users/kent/ in ()

: Asserted false

This is the form with an optional expression and works the way you want.


In [14]: assert 3 < 2, "Bad math"
---
AssertionErrorTraceback (most recent call last)

E:\Python25\Scripts\ in ()

AssertionError: Bad math

In [15]:

Yes.

Thanks, Kent.

Dick 


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


Re: [Tutor] Another assert() question

2008-07-12 Thread Dick Moores

At 01:24 PM 7/12/2008, Danny Yoo wrote:

Content-Transfer-Encoding: 7bit
Content-Disposition: inline

> In my code I have
>
> assert(len(list(set(colors_used_this_cycle))) ==
> len(colors_used_this_cycle), "A color has been used twice!")
>
> But it doesn't work. Cases where a color has been used more than once go
> right through it


Let's try a simple example.


Go back to the structure of an assert statement.

assert condition[, expression]   ## template

Let's think of a very simple condition.  How about False?  Let's
replace the "condition" part above with False, and not provide an
expression yet.

>>> assert False
Traceback (most recent call last):
  File "", line 1, in 
AssertionError


Ok, good.  Now let's try to also fill in an expression.  Let's have
the expression be "I expected this".  So we look back at our template:

assert condition[, expression]   ## template

We're going to substitute False as our condition, and "I expected
this" as our expression.


>>> assert False, "I expected this."
Traceback (most recent call last):
  File "", line 1, in 
AssertionError: I expected this.


That also seems to work.

If the expression gets a little more complicated, the form of the
assertion statement still stays the same.  Let's say that we're
checking to see that the square root of -1 is 1j.  The condition we're
checking is:

(cmath.sqrt(-1) == 1j)

and the expression is "Bad math."  Then:

>>> import cmath
>>> assert (cmath.sqrt(-1) == 1j), "Bad math"
>>>

We didn't see anything, so the assertion's condition is true.  Let's
artificially induce it to fail.


>>> assert (cmath.sqrt(1) == 1j), "Bad math"
Traceback (most recent call last):
  File "", line 1, in 
AssertionError: Bad math


Can you go through a similar exercise with your own condition and
expression?  Isolate the condition part of what you want to test, the
expression part that you want to show, and then just plug directly
into the assert template.


You can see my solution at 
, the highlighted line, line 117.



(The problem here is that you've run across one of the edge cases in
Python's syntax involving parenthesized expressions.  Anyone who says
that you can disregard parentheses in Python is not telling the
truth.)


Thanks for all all those easy steps, Danny. Very clear.

Dick


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


Re: [Tutor] Another assert() question

2008-07-12 Thread Dick Moores

At 01:28 PM 7/12/2008, Michiel Overtoom wrote:

Dick wrote:

> I was hoping to put some sort of explanation of failure in an
> assert statement. But how to do it?
> So I'd like to know what that 'expression' in the syntax can be,
> and how to use it.

I think it would help if you separate the detection of duplicate colors from
the assert statement.


Given the name of the list variable, and the expression "Used a color twice!",
it doesn't seem necessary. But maybe I'm missing something.


It all looks a bit convoluted now, and I'm missing the context in which this
all happens.


Here it is. 


First detect the presence of duplicate colors in a True/False variable, then
use that variable in an assert.

Oh, and by the way, you don't have to convert a set to list to be able to
take it's length.


I'm glad to know that. Thanks!


  colors=["red","blue","green","blue","yellow","blue"]
  duplicatesfound = len(set(colors)) != len(colors)
  assert not duplicatesfound, "A color has been used more than once"

Exercise left for the reader: Report which colors were used more than once.


For this program, I don't care. But I'll work on it.


And do me a favor, post in plain text, not HTML.


HTML? Please explain.

Dick 


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


Re: [Tutor] Another assert() question

2008-07-12 Thread Kent Johnson
On Sat, Jul 12, 2008 at 4:01 PM, Dick Moores <[EMAIL PROTECTED]> wrote:
> _Python in a NutShell_, p. 138 has a bit on the assert statement which I
> don't completely understand.
>
> It says the syntax is
>
> assert condition[, expression]
>
> I was hoping to put some sort of explanation of failure in an assert
> statement. But how to do it?
>
> In my code I have
>
> assert(len(list(set(colors_used_this_cycle))) ==
> len(colors_used_this_cycle), "A color has been used twice!")

Leave out the outermost parentheses, assert is a statement, not a function call.

In [2]: assert(False, "Asserted false")

This is "assert condition" where the condition is a tuple with two
elements, hence true so there is no output.

In [3]: assert False, "Asserted false"
---
Traceback (most recent call last)

/Users/kent/ in ()

: Asserted false

This is the form with an optional expression and works the way you want.

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


Re: [Tutor] Classes v2, thoughts/suggestions please

2008-07-12 Thread Kent Johnson
On Sat, Jul 12, 2008 at 9:47 AM, Paul Melvin
<[EMAIL PROTECTED]> wrote:

> And how can i go about testing that i get appropriate values during the
> testing/building phase (generally speaking), is it lots of print/return
> statements and then remove them?

Take a look at the doctest and unittest modules, that is a better approach.

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


Re: [Tutor] Another assert() question

2008-07-12 Thread Michiel Overtoom
Dick wrote:

> I was hoping to put some sort of explanation of failure in an 
> assert statement. But how to do it?
> So I'd like to know what that 'expression' in the syntax can be, 
> and how to use it.

I think it would help if you separate the detection of duplicate colors from
the assert statement.
It all looks a bit convoluted now, and I'm missing the context in which this
all happens.
First detect the presence of duplicate colors in a True/False variable, then
use that variable in an assert.

Oh, and by the way, you don't have to convert a set to list to be able to
take it's length.

  colors=["red","blue","green","blue","yellow","blue"]
  duplicatesfound = len(set(colors)) != len(colors)
  assert not duplicatesfound, "A color has been used more than once"

Exercise left for the reader: Report which colors were used more than once.

And do me a favor, post in plain text, not HTML.

Greetings,

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html

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


Re: [Tutor] Another assert() question

2008-07-12 Thread Danny Yoo
> In my code I have
>
> assert(len(list(set(colors_used_this_cycle))) ==
> len(colors_used_this_cycle), "A color has been used twice!")
>
> But it doesn't work. Cases where a color has been used more than once go
> right through it


Let's try a simple example.


Go back to the structure of an assert statement.

assert condition[, expression]   ## template

Let's think of a very simple condition.  How about False?  Let's
replace the "condition" part above with False, and not provide an
expression yet.

>>> assert False
Traceback (most recent call last):
  File "", line 1, in 
AssertionError


Ok, good.  Now let's try to also fill in an expression.  Let's have
the expression be "I expected this".  So we look back at our template:

assert condition[, expression]   ## template

We're going to substitute False as our condition, and "I expected
this" as our expression.


>>> assert False, "I expected this."
Traceback (most recent call last):
  File "", line 1, in 
AssertionError: I expected this.


That also seems to work.

If the expression gets a little more complicated, the form of the
assertion statement still stays the same.  Let's say that we're
checking to see that the square root of -1 is 1j.  The condition we're
checking is:

(cmath.sqrt(-1) == 1j)

and the expression is "Bad math."  Then:

>>> import cmath
>>> assert (cmath.sqrt(-1) == 1j), "Bad math"
>>>

We didn't see anything, so the assertion's condition is true.  Let's
artificially induce it to fail.


>>> assert (cmath.sqrt(1) == 1j), "Bad math"
Traceback (most recent call last):
  File "", line 1, in 
AssertionError: Bad math


Can you go through a similar exercise with your own condition and
expression?  Isolate the condition part of what you want to test, the
expression part that you want to show, and then just plug directly
into the assert template.



(The problem here is that you've run across one of the edge cases in
Python's syntax involving parenthesized expressions.  Anyone who says
that you can disregard parentheses in Python is not telling the
truth.)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Another assert() question

2008-07-12 Thread Dick Moores


_Python in a NutShell_, p. 138 has a bit on the assert statement which I
don't completely understand.
It says the syntax is
assert condition[, _expression_]
I was hoping to put some sort of explanation of failure in an assert
statement. But how to do it?
In my code I have
assert(len(list(set(colors_used_this_cycle))) ==
len(colors_used_this_cycle), "A color has been used
twice!")
But it doesn't work. Cases where a color has been used more than
once go right through it, whereas
colors_used_this_cycle.append(color)
assert(len(list(set(colors_used_this_cycle))) ==
len(colors_used_this_cycle)
works perfectly.
So I'd like to know what that '_expression_' in the syntax can be, and how
to use it.
Thanks,
Dick Moores


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


Re: [Tutor] Classes v2, thoughts/suggestions please

2008-07-12 Thread Paul Melvin
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
> Behalf Of Alan Gauld
> Sent: 12 July 2008 18:08
> To: tutor@python.org
> Subject: Re: [Tutor] Classes v2, thoughts/suggestions please
> 
> 
> "Paul Melvin" <[EMAIL PROTECTED]> wrote
> 
> >  i have come up with a working class for a square,
> 
> Well done. It might not be the most elegant solution on the
> inside but it isn't too bad from the users point of view and thats
> what you should aim for IMHO.
> 
> > I was thinking about using *args to get maybe the colour
> > information in,
> 
> I would define polygon to take a list of points as a parameter
> of init so you put the onus on the user to pass in  tbe points
> in a list. That makes the init method easy:
> 
> Class Polygon:
> def __init__(self, pList, filled=True, line_width=1):
> self.points = pList
> self.filled = filled
> self.line_width = line_width
> 
> Your draw method is as before but instead of repeating
> the code 4 times just put it into a loop that iterates over
> the points list, something like:
> 
> def draw(self):
> if self.filled:
> glBegin(GL_QUADS)
> else:
> glLineWidth(self.line_width)
> glBegin(GL_LINE_LOOP)
> for p in self.pList
> glColor4f(p.col[0], p.col[1], p.col[2], p.col[3])
> glVertex2i(int(p.x), int(p.y))
> glEnd()
> if not filled and line_width != 1:  # reset to default
> glLineWidth(1)
> 
> Note that I put it as the draw method not as a separate
> function. There is little point in having a class then calling
> a separate function to which you have to pass all the
> data in the class!
> 
> > And how can i go about testing that i get appropriate values during
> > the
> > testing/building phase (generally speaking), is it lots of
> > print/return
> > statements and then remove them?
> 
> I'm not sure what you mean by "appropriate values" in this context.
> Since you are drawing graphics I suspect you will have to just
> draw them in a simple canvas and visually ensure the result is
> what you expect?
> 
> You could try implementing a __str__ method in each class that
> lets you print out a nicely formatted report of the Point and/or
> Polygon data, which would allow you to do:
> 
> p = Point(.)
> print p
> s = Polygon([p,p2,p3,p4])
> print s
> 
> That would allow you to see what the graphic parameters will
> be before drawing.
> 
> HTH,
> 
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
> 
Thanks again for your help, as for 'appropriate' values, in this specific
case it would be numbers but I am also interested in the general design
process, ie how you check your code during design/coding, is it print
statements for example?

Before I start on my polygon class, Alan did mention that it was not
'elegant' which i know as I am only starting and I thought of it as dirty
but working, can someone tell me how I could improve this code or write
better code in the future

Cheers

paul
 

__ Information from ESET Smart Security, version of virus signature
database 3263 (20080711) __

The message was checked by ESET Smart Security.

http://www.eset.com
 

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


Re: [Tutor] Classes v2, thoughts/suggestions please

2008-07-12 Thread Alan Gauld


"Paul Melvin" <[EMAIL PROTECTED]> wrote


 i have come up with a working class for a square,


Well done. It might not be the most elegant solution on the
inside but it isn't too bad from the users point of view and thats
what you should aim for IMHO.


I was thinking about using *args to get maybe the colour
information in,


I would define polygon to take a list of points as a parameter
of init so you put the onus on the user to pass in  tbe points
in a list. That makes the init method easy:

Class Polygon:
   def __init__(self, pList, filled=True, line_width=1):
   self.points = pList
   self.filled = filled
   self.line_width = line_width

Your draw method is as before but instead of repeating
the code 4 times just put it into a loop that iterates over
the points list, something like:

def draw(self):
   if self.filled:
   glBegin(GL_QUADS)
   else:
   glLineWidth(self.line_width)
   glBegin(GL_LINE_LOOP)
   for p in self.pList
   glColor4f(p.col[0], p.col[1], p.col[2], p.col[3])
   glVertex2i(int(p.x), int(p.y))
   glEnd()
   if not filled and line_width != 1:  # reset to default
   glLineWidth(1)

Note that I put it as the draw method not as a separate
function. There is little point in having a class then calling
a separate function to which you have to pass all the
data in the class!

And how can i go about testing that i get appropriate values during 
the
testing/building phase (generally speaking), is it lots of 
print/return

statements and then remove them?


I'm not sure what you mean by "appropriate values" in this context.
Since you are drawing graphics I suspect you will have to just
draw them in a simple canvas and visually ensure the result is
what you expect?

You could try implementing a __str__ method in each class that
lets you print out a nicely formatted report of the Point and/or
Polygon data, which would allow you to do:

p = Point(.)
print p
s = Polygon([p,p2,p3,p4])
print s

That would allow you to see what the graphic parameters will
be before drawing.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



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


Re: [Tutor] splits and pops

2008-07-12 Thread Marcel Wunderlich

Hi Eric,

I tried following and it seems to work:

fullstring = """l1r1 ll1r2   l1r3l1
r4  l1r5
l2r1l2r3l3
r3  l2r4l2r5
l3r1l3r2l3r3l3r4l3r5
"""
# This should be a string like your's. "\t"-seperated columns,  
"\n"-seperated

# rows, with "\n" in some columns.

rowlength = 5
# for you it would be 9, but I was lazy when I wrote the string

prefetch = ""
lines = []
i = 0
for tab in fullstring.split("\t"):
if i < rowlength-1:  #i.e. working on all but the last column
# offtopic: is the last comment correct English?
prefetch += tab + "\t" # +"\t" because split removes the tab
i += 1
else: # last column
prefetch += tab[:tab.find("\n")]
lines.append(prefetch)
		prefetch = tab[(tab.find("\n")+2):] #adding the first column without the  
"\n"

i = 1 #since we already added the first column

# End

After that "print lines" produces following output:
['l1r1\tll1r2\tl1r3\tl1\nr4\tl1r5', '2r1l2r3\tl3\nr3\tl2r4\tl2r5',  
'3r1l3r2\tl3r3\tl3r4\tl3r5']

So you've got a list of the lines. Instead of Strings you could also use
lists, by making prefetch a list and instead of adding the tabs, appending  
it.


However, I assumed that the new row is seperated by the first linebreak.
If that's not the case, I think that you have to check for multiple  
linebreaks

and if that's true, choose manually which one to select.

Hope this helps,

Marcel

I have a horribly stupid text parsing problem that is driving me crazy,  
and making me think my Python skills have a long, long way to go...


What I've got is a poorly-though-out SQL dump, in the form of a text  
file, where each record is separated by a newline, and each field in  
each record is separated by a tab. BUT, and this is what sinks me, there  
are also newlines within some of the fields. Newlines are not 'safe' –  
they could appear anywhere – but tabs are 'safe' – they only appear as  
field delimiters.


There are nine fields per record. All I can think to do is read the file  
in as a string, then split on tabs. That gives me a list where every  
eighth item is a string like this: u'last-field\nfirst-field'. Now I  
want to iterate through the list of strings, taking every eighth item,  
splitting it on '\n', and replacing it with the two resulting strings.  
Then I'll have the proper flat list where every nine list items  
constitutes one complete record, and I'm good to go from there.


I've been fooling around with variations on the following (assuming  
splitlist = fullstring.split('\t')):


for x in xrange(8, sys.maxint, 8):
 try:
 splitlist[x:x] = splitlist.pop(x).split('\n')
 except IndexError:
 break

The first line correctly steps over all the list items that need to be  
split, but I can't come up with a line that correctly replaces those  
list items with the two strings I want. Either the cycle goes off and  
splits the wrong strings, or I get nested list items, which is not what  
I want. Can someone please point me in the right direction here?


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



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


Re: [Tutor] splits and pops

2008-07-12 Thread Kent Johnson
On Sat, Jul 12, 2008 at 8:55 AM, Eric Abrahamsen
<[EMAIL PROTECTED]> wrote:

> I've been fooling around with variations on the following (assuming
> splitlist = fullstring.split('\t')):
>
> for x in xrange(8, sys.maxint, 8):
>try:
>splitlist[x:x] = splitlist.pop(x).split('\n')
>except IndexError:
>break
>
> The first line correctly steps over all the list items that need to be
> split, but I can't come up with a line that correctly replaces those list
> items with the two strings I want. Either the cycle goes off and splits the
> wrong strings, or I get nested list items, which is not what I want. Can
> someone please point me in the right direction here?

The problem is that once you substitute a split field, the indices of
the remaining fields change so you are not looking at the right ones.
Some possibilities:
- work from the back of the list so the indices of the fields to be
processed don't change
- build a new list as you go
- keep track of an offset that you add to the index

The second one would be something like this (untested):
result = []
for i, value in enumerate(splitlist):
  if (i+1) % 8 == 0:
result.extend(value.split('\n'))
  else:
result.append(value)

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


Re: [Tutor] splits and pops

2008-07-12 Thread bob gailer
Please reply to the list and not just me. That way we all get to 
contribute and to learn.


Eric Abrahamsen wrote:
Sorry I haven't explained this clearly, it's just one more symptom of 
my confusion... Your example has a tab between records as well as 
between fields: 


That's not how I see it! Look again:

"11\t12\t13\t\n14\t15\t16\t17\t18\t19\n21\t22\t23\t24\t25\t26\t27\t28\t29"

my text file had tabs only between fields, and only a newline between 
records.


The test string I was practicing with was this:

test = 'one\ttwo\tthree\nfour\tfive\tsix'

split on tabs produced this:

test = ['one', 'two', 'three\nfour', 'five', 'six']

My loop (breaking test[2] on '\n') worked fine with this test, which 
was what confused me. I only realized what the problem was when I 
tried it on a test like this:


test = ['one', 'two', 'three\nfour', 'five', 'six', 'seven\neight', 
'nine']


That showed me that I needed to step one extra item, in order to reach 
the next item that needed to be split. My brain still hurts.



E

On Jul 12, 2008, at 9:44 PM, bob gailer wrote:


Eric Abrahamsen wrote:
I have a horribly stupid text parsing problem that is driving me 
crazy, and making me think my Python skills have a long, long way to 
go...


What I've got is a poorly-though-out SQL dump, in the form of a text 
file, where each record is separated by a newline, and each field in 
each record is separated by a tab. BUT, and this is what sinks me, 
there are also newlines within some of the fields. Newlines are not 
'safe' – they could appear anywhere – but tabs are 'safe' – they 
only appear as field delimiters.


There are nine fields per record. All I can think to do is read the 
file in as a string, then split on tabs. That gives me a list where 
every eighth item is a string like this: u'last-field\nfirst-field'. 
Now I want to iterate through the list of strings, taking every 
eighth item, splitting it on '\n', and replacing it with the two 
resulting strings. Then I'll have the proper flat list where every 
nine list items constitutes one complete record, and I'm good to go 
from there.


I've been fooling around with variations on the following (assuming 
splitlist = fullstring.split('\t')):


for x in xrange(8, sys.maxint, 8):
   try:
   splitlist[x:x] = splitlist.pop(x).split('\n')
   except IndexError:
   break

The first line correctly steps over all the list items that need to 
be split, but I can't come up with a line that correctly replaces 
those list items with the two strings I want. Either the cycle goes 
off and splits the wrong strings, or I get nested list items, which 
is not what I want. Can someone please point me in the right 
direction here?
I  tried a simple case with fullstring = 
"11\t12\t13\t\n14\t15\t16\t17\t18\t19\n21\t22\t23\t24\t25\t26\t27\t28\t29" 

Your spec is a little vague "each field in each record is separated 
by a tab". I assumed that to mean "fields in each record are 
separated by tabs".
The result was ['11', '12', '13', '\n14', '15', '16', '17', '18', 
'19', '21', '22', '23', '24', '25', '26', '27', '28', '29']

which I had expected.

Give us an example of text for which it does not work.






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







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

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


[Tutor] Classes v2, thoughts/suggestions please

2008-07-12 Thread Paul Melvin
Thanks to Alans insights i have come up with a working class for a square,
overcomplicated probably but it lays the groundwork for my polygon class
which will iterate over something to generate an n-sided polygon.
If anyone is interested in actually running/testing this you need to get
hold of pgylet 1.1, http://pyglet.org/
I would welcome any suggestions/improvements etc as my class knowledge is
still somewhat lacking :-) 
I was thinking about using *args to get maybe the colour information in, not
sure if i could do it with the points, is this a good idea/possible?
And how can i go about testing that i get appropriate values during the
testing/building phase (generally speaking), is it lots of print/return
statements and then remove them?
Thanks
paul
#!/usr/bin/env python

from pyglet.gl import *

class Point:
'''This init contains the x,y co-ordinates
   and the colour/transparency objects
   cr is red, cg is green, cb is blue and ct is transparency
   a value or 1.0, 1.0, 1.0, 1.0 is white/0% transparent'''
def __init__(self, x=0, y=0, cr=1.0, cg=1.0, cb=1.0, ct=1.0):
self.x = x
self.y = y
self.cr = cr
self.cg = cg
self.cb = cb
self.ct = ct
self.col = (cr, cg, cb, ct)

class Square:
'''First version, requires four points, an optional filled field
   and an optional line width field.
   The next version will iterate over a loop to allow the
   construction of polygons'''
def __init__(self, p1, p2, p3, p4, filled=True, line_width=1):
self.points = [p1,p2,p3,p4]
self.filled = filled
self.line_width = line_width
def draw(self):
draw_square(self.points[0].x, self.points[0].y, self.points[0].col,
self.points[1].x,self.points[1].y, self.points[1].col, self.points[2].x,
self.points[2].y, self.points[2].col, self.points[3].x, self.points[3].y,
self.points[3].col, self.filled, self.line_width)

def draw_square(x0, y0, col0, x1, y1, col1, x2, y2, col2, x3, y3, col3,
filled=True, line_width=1):

if filled:
glBegin(GL_QUADS)
else:
glLineWidth(line_width)
glBegin(GL_LINE_LOOP)

glColor4f(col0[0], col0[1], col0[2], col0[3])
glVertex2i(int(x0), int(y0))
glColor4f(col1[0], col1[1], col1[2], col1[3])
glVertex2i(int(x1), int(y1))
glColor4f(col2[0], col2[1], col2[2], col2[3])
glVertex2i(int(x2), int(y2))
glColor4f(col3[0], col3[1], col3[2], col3[3])
glVertex2i(int(x3), int(y3))
glEnd()
if not filled and line_width != 1:  # reset to default
glLineWidth(1)

if __name__ == '__main__':
from pyglet import window

window  = window.Window(250, 250)
s1 = Square(Point(50,50,cg=0.0,cb=0.0), Point(200,50,cr=0.0,cb=0.0),
Point(200,200,cr=0.0,cg=0.0), Point(50,200), filled=False, line_width=2)

@window.event
def on_draw():
window.clear()
s1.draw()

pyglet.app.run()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] splits and pops

2008-07-12 Thread bob gailer

Eric Abrahamsen wrote:
I have a horribly stupid text parsing problem that is driving me 
crazy, and making me think my Python skills have a long, long way to 
go...


What I've got is a poorly-though-out SQL dump, in the form of a text 
file, where each record is separated by a newline, and each field in 
each record is separated by a tab. BUT, and this is what sinks me, 
there are also newlines within some of the fields. Newlines are not 
'safe' – they could appear anywhere – but tabs are 'safe' – they only 
appear as field delimiters.


There are nine fields per record. All I can think to do is read the 
file in as a string, then split on tabs. That gives me a list where 
every eighth item is a string like this: u'last-field\nfirst-field'. 
Now I want to iterate through the list of strings, taking every eighth 
item, splitting it on '\n', and replacing it with the two resulting 
strings. Then I'll have the proper flat list where every nine list 
items constitutes one complete record, and I'm good to go from there.


I've been fooling around with variations on the following (assuming 
splitlist = fullstring.split('\t')):


for x in xrange(8, sys.maxint, 8):
try:
splitlist[x:x] = splitlist.pop(x).split('\n')
except IndexError:
break

The first line correctly steps over all the list items that need to be 
split, but I can't come up with a line that correctly replaces those 
list items with the two strings I want. Either the cycle goes off and 
splits the wrong strings, or I get nested list items, which is not 
what I want. Can someone please point me in the right direction here? 
I  tried a simple case with fullstring = 
"11\t12\t13\t\n14\t15\t16\t17\t18\t19\n21\t22\t23\t24\t25\t26\t27\t28\t29"
Your spec is a little vague "each field in each record is separated by a 
tab". I assumed that to mean "fields in each record are separated by tabs".
The result was ['11', '12', '13', '\n14', '15', '16', '17', '18', '19', 
'21', '22', '23', '24', '25', '26', '27', '28', '29']

which I had expected.

Give us an example of text for which it does not work.






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

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


[Tutor] splits and pops

2008-07-12 Thread Eric Abrahamsen
I have a horribly stupid text parsing problem that is driving me  
crazy, and making me think my Python skills have a long, long way to  
go...


What I've got is a poorly-though-out SQL dump, in the form of a text  
file, where each record is separated by a newline, and each field in  
each record is separated by a tab. BUT, and this is what sinks me,  
there are also newlines within some of the fields. Newlines are not  
'safe' – they could appear anywhere – but tabs are 'safe' – they only  
appear as field delimiters.


There are nine fields per record. All I can think to do is read the  
file in as a string, then split on tabs. That gives me a list where  
every eighth item is a string like this: u'last-field\nfirst-field'.  
Now I want to iterate through the list of strings, taking every eighth  
item, splitting it on '\n', and replacing it with the two resulting  
strings. Then I'll have the proper flat list where every nine list  
items constitutes one complete record, and I'm good to go from there.


I've been fooling around with variations on the following (assuming  
splitlist = fullstring.split('\t')):


for x in xrange(8, sys.maxint, 8):
try:
splitlist[x:x] = splitlist.pop(x).split('\n')
except IndexError:
break

The first line correctly steps over all the list items that need to be  
split, but I can't come up with a line that correctly replaces those  
list items with the two strings I want. Either the cycle goes off and  
splits the wrong strings, or I get nested list items, which is not  
what I want. Can someone please point me in the right direction here?


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


Re: [Tutor] Classes

2008-07-12 Thread Alan Gauld


"Alan Gauld" <[EMAIL PROTECTED]> wrote 


class Square:
def __init__(self,p1,p2,p3,p4):
 self.points = [p1,p2,p3,p4]
def draw(self):
 myTookKitDrawSquare(p1.x,p1.y, p1.col,
   p2.x,p2.y, p2.col,
   p3.x,p3.y, p3.col,
   p4.x,p4.y, p4.col)


Oops! The p1.x etc should of course have been
self.points[0].x etc draw cannot use the point
parameters from init! 


Alan G.

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


Re: [Tutor] Launching default web browsers.

2008-07-12 Thread Alan Gauld


"ammar azif" <[EMAIL PROTECTED]> wrote


I am going to develop an application that will launch the
user's computer default web browser pointing to a URL.
 How to do this in python and which library should I use?


Look at the webbrowser module, it is intended to do just that.


Also, my development platform is Linux but the application
is targeted to run in Windows platform. Is there any major
platform dependent barriers that I will face?


There will almost inevitably be some issues but a lot will
depend on the browsers in use as well. If everyone is using
Firefox or IE then its likely to work fairly well, but if there
is a big mix of browsers I suspect you might have some
headaches.

I suggest you try a very simple script initially and see how
well it works with your users.

Alan G









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




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