Re: [Tutor] stumped again adding bytes

2007-02-23 Thread Alan Gauld

"shawn bright" <[EMAIL PROTECTED]> wrote 

> if i use i bitmask of 240 it will mask the most significant 4 bits

When using bitmasks its much easier to think in hex (or octal).
there are exactly 2 hex digits per byte so you only need to think 
about each group of 4 bits and its hex bit pattern. It saves a 
heap of mental calculations!

Alan G.

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


Re: [Tutor] stumped again adding bytes

2007-02-23 Thread Alan Gauld

"shawn bright" <[EMAIL PROTECTED]> wrote


> so i believe i do shifting here. as in i do a
> (a << 4) * 32 + b
>

Don't use shifting to extract the bits, use a bitmask
and & its much easier.

If you want to extract the left-most 4 bits use 0xf0
If you want to extract the righ-most bits use 0x0f

1 & 1 = 1
1 & 0 = 0

Or more generically:

1 & A = A

right = data & 0xf0
left = data & 0x0f

As easy as that.

Now if you need to stich the bits together you need to move
one element up by 4 bits which is where shifting comes in.

result = (data << 4) & right

> but i am not getting what i think that i should be, and i think it's
> because i am not getting rid of the bytes that i am not using.

Its easier to extract the bits into a new variable using a mask
as shown.

> i have looked at the struct module, but can't figgure out how to do
> this type of thing with it.

This is not what struct is for, don't try uising it for this. even if
you make it work its not the best tool.

Alan G. 


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


Re: [Tutor] Dictionaries of Tuples of Strings

2007-02-23 Thread Bill Sconce
On Fri, 23 Feb 2007 13:45:54 -0800 (PST)
Terry Carroll <[EMAIL PROTECTED]> wrote:

> > Any other way to create an empty tuple? 
> 
> Answering my own question:
> 
> >>> t=()
> >>> type(t)
> 


Giving the lie to my earlier summary (that tuples are
indicated by commas only -- arrgh  :)
__
All right, then, let's get it right.  From THE tutorial (in the kit):
A tuple consists of a number of values separated by commas,
for instance:
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
...As you see, on output tuples are always enclosed in parentheses,
so that nested tuples are interpreted correctly; they may be input
with or without surrounding parentheses, although often parentheses
are necessary anyway (if the tuple is part of a larger expression).

...A special problem is the construction of tuples containing 0 
or 1 items: the syntax has some extra quirks to accommodate these.
Empty tuples are constructed by an empty pair of parentheses; 
a tuple with one item is constructed by following a value with
a comma (it is not sufficient to enclose a single value in
parentheses). Ugly, but effective.
  
in the original :)

>>> empty = ()
>>> singleton = 'hello',# <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)

 
 
HTH,

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


Re: [Tutor] Programming the behavior of a set of domino

2007-02-23 Thread Bob Gailer
Chung-hong Chan wrote:
> Hello,
>
> I am a newbie in computer programming and I am also not a native
> English Speaker. I love to play domino and I would like to program a
> simple domino game in python. Also a good opportunity for me to learn
> some computer programming.
> I need some help in my code which programming the behaviors of a set of 
> domino.
> Here is the code, generally a modification of the code from the deck
> of card example in How to Think like a Computer Scientist.
>
> #!/usr/bin/python
> class domino:
>   
It is a convention in Python to capiatlize class names (e.g. class Domino)
>   def __init__(self,a_end,b_end):
>   self.a_end=a_end
>   self.b_end=b_end
>   def __str__(self):
>   return ("["+str(self.a_end)+","+str(self.b_end)+"]")
>   def __cmp__(self,other):
>   if self.a_end==other.b_end and self.b_end==other.a_end:
>   return 0
>   return 1
>
> class deck:
>   def __init__(self,set_type):
>   self.dominoes = []
>   self.set_type = set_type
>   for a_end in range(self.set_type+1):
>   for b_end in range(self.set_type+1):
>   self.dominoes.append(domino(a_end,b_end))
>   def print_deck(self):
>   for domino in self.dominoes:
>   print domino
>   def deck_len(self):
>   print len(self.dominoes)
>
>
> newdomino = deck(12)
> newdomino.print_deck()
> newdomino.deck_len()
>
> if domino(1,2)==domino(2,2):
>   print "yes"
> else:
>   print "no"
>
> each piece of domino have a_end and b_end. domino (1,2) and
> domino(2,1) is the same and thus one of them should be removed. Now,
> deck(12) will return 169 dominoes while the expected number of
> dominoes is 91. Even I wrote a __cmp__ method for domino, list
> membership (i.e. x in list) is not working because they are not a
> exact duplicates.
>   
To create only unique dominoes:

for a_end in range(self.set_type+1):
for b_end in range(a_end, self.set_type+1):
self.dominoes.append(domino(a_end,b_end))

> Can anyone shed me some light to solve this problem?

-- 
Bob Gailer
510-978-4454

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


Re: [Tutor] Dictionaries of Tuples of Strings

2007-02-23 Thread Luke Paireepinart
Terry Carroll wrote:
> On Fri, 23 Feb 2007, Luke Paireepinart wrote:
>
>   
>> That's because you can't make tuples of single values.
>> Think of it like this:
>> a TUple needs TWO elements or more.
>> 
>
> No, a tuple can also be of one element, or even none.  You can create a
> single-element tuple either directly through the use of a trailing comma,
> or via the tuple() method:
>
>   
 t = "x", # but this looks like a syntax error or a continued line
 t = ("x",)   # I think this is a little clearer, but still ugly
 t = tuple("x")   # my preference
 
>
>   
 >>> x = tuple("hello")
 >>> x
('h', 'e', 'l', 'l', 'o')

It apparently doesn't work that way with iterables.
I think the 'way you'd expect it to work' using your preference is to create
('hello')
but if you're doing intergers or single-character strings, it shouldn't 
matter either way.

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


Re: [Tutor] stumped again adding bytes

2007-02-23 Thread shawn bright
whoops, meant this to the list, sorry Luke.

On 2/23/07, shawn bright <[EMAIL PROTECTED]> wrote:
> Thanks for your help, Luke.
> i am trying to get a grasp on how all this works, which is the msb, lsb, etc..
>
> if i use i bitmask of 240 it will mask the most significant 4 bits
> so that only the most significant 4 bits remain..
> like 53 & 240 = 48 ( because only the 32 and 16 are set)
> and if i use 15 it should mask the least significant bits, right ?
>
> now if i am using the first half of the 2nd byte, and making the first
> byte the most significant.
> i would shift the first byte to the Left by 4
> byte1 << 4  then add ( byte2 & 240 )
>
> so for the next number that i want that will consist of the 2nd half
> of the 2nd byte as the most significant , i would take the second byte
> with my bitmask then shift it right by 4 then add the third byte to
> that  am i getting this right
> like x = ((byte2 & 240) << 4) + byte 3
>
> i think ?
>
> shawn
>
>
> On 2/23/07, Luke Paireepinart <[EMAIL PROTECTED]> wrote:
> > shawn bright wrote:
> > > ok, i am good with what you have explained here,
> > > now i am on a similar problem.
> > >
> > > the data i need is in a condensed format. in other words, they are
> > > sending 2 values in three bytes.
> > >
> > > so if i have 3 values say a = 53, b = 13, and c = 31
> > >
> > > so value 1 is the first byte ( a ) and the first 4 bits of the second
> > > byte (b)
> > > value 2 is the last 4 bits of byte (b) and byte (c)
> > Please try not to interchange your terms, it makes your questions confusing.
> > 'so if i have 3 values say a = 53, b = 13, and c = 31'
> > Should be 'so if I have 3 bytes'
> > because immediately after, you talk about your extracted data as 'values.'
> > It's not too big of a deal, but it was confusing at first.
> > >
> > > so i believe i do shifting here. as in i do a
> > > (a << 4) * 32 + b
> > You need to read an article on bit manipulation.
> > I'll give you a summary of what you're trying to do.
> > given the byte
> > x = 1 1 0 0 0 1 1 0
> > If you want to extract just the four most significant bits, [1 1 0 0],
> > you shift the number TO THE RIGHT by 4.
> > x >> 4
> > will result in 4 shifts like so:
> > 1 1 0 0 0 1 1 0 -> 1 1 0 0 0 1 1
> > 1 1 0 0 0 1 1 -> 1 1 0 0 0 1
> > 1 1 0 0 0 1 -> 1 1 0 0 0
> > 1 1 0 0 0 -> 1 1 0 0
> > Which results in the number 0x0C or 12.
> > Now, since these are the MSB, you could shift back 4 places
> > x << 4
> > 1 1 0 0 -> 1 1 0 0 0
> > 1 1 0 0 0 -> 1 1 0 0 0 0
> > 1 1 0 0 0 0 -> 1 1 0 0 0 0 0
> > 1 1 0 0 0 0 0 -> 1 1 0 0 0 0 0 0
> >
> > but I don't know if you want to do that or not.
> > and if you wanted to do that, you could just use a bitmask from the
> > beginning.  see the next part.
> >
> > Now as for the least significant bits:
> > recall that
> >
> > 1 1 0 0 0 1 0 0 & 0 0 0 0 1 1 1 1
> > will yeild
> > 0 0 0 0 + whatever the last 4 bits are in the first item.
> >
> > Hope that helps.
> > It's better if you take the time to really understand what is happening
> > in all these cases, so you won't have to experiment with trial and error.
> > -Luke
> >
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionaries of Tuples of Strings

2007-02-23 Thread Terry Carroll
On Fri, 23 Feb 2007, Terry Carroll wrote:

> You can also create an empty tuple, but I think only through the tuple() 
> method:
> >>> t=tuple()
>  
> Any other way to create an empty tuple? 

Answering my own question:

>>> t=()
>>> type(t)


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


Re: [Tutor] stumped again adding bytes

2007-02-23 Thread shawn bright
Thanks for your help, Luke.
i am trying to get a grasp on how all this works, which is the msb, lsb, etc..

if i use i bitmask of 240 it will mask the most significant 4 bits
so that only the most significant 4 bits remain..
like 53 & 240 = 48 ( because only the 32 and 16 are set)
and if i use 15 it should mask the least significant bits, right ?

now if i am using the first half of the 2nd byte, and making the first
byte the most significant.
i would shift the first byte to the Left by 4
byte1 << 4  then add ( byte2 & 240 )

so for the next number that i want that will consist of the 2nd half
of the 2nd byte as the most significant , i would take the second byte
with my bitmask then shift it right by 4 then add the third byte to
that  am i getting this right
like x = ((byte2 & 240) << 4) + byte 3

i think ?

shawn


On 2/23/07, Luke Paireepinart <[EMAIL PROTECTED]> wrote:
> shawn bright wrote:
> > ok, i am good with what you have explained here,
> > now i am on a similar problem.
> >
> > the data i need is in a condensed format. in other words, they are
> > sending 2 values in three bytes.
> >
> > so if i have 3 values say a = 53, b = 13, and c = 31
> >
> > so value 1 is the first byte ( a ) and the first 4 bits of the second
> > byte (b)
> > value 2 is the last 4 bits of byte (b) and byte (c)
> Please try not to interchange your terms, it makes your questions confusing.
> 'so if i have 3 values say a = 53, b = 13, and c = 31'
> Should be 'so if I have 3 bytes'
> because immediately after, you talk about your extracted data as 'values.'
> It's not too big of a deal, but it was confusing at first.
> >
> > so i believe i do shifting here. as in i do a
> > (a << 4) * 32 + b
> You need to read an article on bit manipulation.
> I'll give you a summary of what you're trying to do.
> given the byte
> x = 1 1 0 0 0 1 1 0
> If you want to extract just the four most significant bits, [1 1 0 0],
> you shift the number TO THE RIGHT by 4.
> x >> 4
> will result in 4 shifts like so:
> 1 1 0 0 0 1 1 0 -> 1 1 0 0 0 1 1
> 1 1 0 0 0 1 1 -> 1 1 0 0 0 1
> 1 1 0 0 0 1 -> 1 1 0 0 0
> 1 1 0 0 0 -> 1 1 0 0
> Which results in the number 0x0C or 12.
> Now, since these are the MSB, you could shift back 4 places
> x << 4
> 1 1 0 0 -> 1 1 0 0 0
> 1 1 0 0 0 -> 1 1 0 0 0 0
> 1 1 0 0 0 0 -> 1 1 0 0 0 0 0
> 1 1 0 0 0 0 0 -> 1 1 0 0 0 0 0 0
>
> but I don't know if you want to do that or not.
> and if you wanted to do that, you could just use a bitmask from the
> beginning.  see the next part.
>
> Now as for the least significant bits:
> recall that
>
> 1 1 0 0 0 1 0 0 & 0 0 0 0 1 1 1 1
> will yeild
> 0 0 0 0 + whatever the last 4 bits are in the first item.
>
> Hope that helps.
> It's better if you take the time to really understand what is happening
> in all these cases, so you won't have to experiment with trial and error.
> -Luke
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionaries of Tuples of Strings

2007-02-23 Thread Terry Carroll
On Fri, 23 Feb 2007, Bill Sconce wrote:

> It's not true that
>parentheses indicate tuples
> (They don't.  Not unless there are "commas in there".)

Except in one case, the empty tuple:

 t = ()

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


Re: [Tutor] Dictionaries of Tuples of Strings

2007-02-23 Thread Terry Carroll
On Fri, 23 Feb 2007, Luke Paireepinart wrote:

> That's because you can't make tuples of single values.
> Think of it like this:
> a TUple needs TWO elements or more.

No, a tuple can also be of one element, or even none.  You can create a
single-element tuple either directly through the use of a trailing comma,
or via the tuple() method:

>>> t = "x", # but this looks like a syntax error or a continued line
>>> t = ("x",)   # I think this is a little clearer, but still ugly
>>> t = tuple("x")   # my preference


You can also create an empty tuple, but I think only through the tuple() 
method:

>>> t = ,
SyntaxError: invalid syntax
>>> t = (,)
SyntaxError: invalid syntax
>>> t=tuple()
 
Any other way to create an empty tuple? 

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


Re: [Tutor] Dictionaries of Tuples of Strings

2007-02-23 Thread Luke Paireepinart
Tim Golden wrote:
> Luke Paireepinart wrote:
>
>> That's because you can't make tuples of single values.
>> Parenthesis are ways of controlling order of operation.
>> They don't create tuples unless there's more than one value.
>
>> Think of it like this:
>> a TUple needs TWO elements or more.
>> Solution:
>> use lists.  They can contain single elements.
>
> Don't know where you got that one from:
>
> 
> t = (1,)
> type (t)
>
> 
>
> In fact, in a certain way, it's the comma which makes the tuple.
> Brackets are only needed in some circs to disambiguate (eg in
> parameter lists to functions)
Ah yes , I forgot about that.  I've seen that before and wondered why 
there was that extra comma.
Oops.
I guess the difference, then, is whether your data collections need to 
be mutable or not.
>

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


Re: [Tutor] Dictionaries of Tuples of Strings

2007-02-23 Thread Bill Sconce
Don't feel bad.  Everyone who works with Python bumps into this.
And more than once...

The preceding reply is correct.  But perhaps this is more specific:

> TYPES_PYTHON_TO_XML = {
>'int':('xs:hexbinary','xs:integer'),
>'str':("xs:string")
>}


The problem is here:
>'str':("xs:string")
This is semantically identical to:
>'str':"xs:string"



Problem corrected:
>'str':("xs:string",)
   ^
 comma
 
It helps to think,
   tuples are made by commas
   parentheses (only) enclose expressions
It's not true that
   parentheses indicate tuples
(They don't.  Not unless there are "commas in there".)


HTH,

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


Re: [Tutor] Dictionaries of Tuples of Strings

2007-02-23 Thread Tim Golden
Luke Paireepinart wrote:

> That's because you can't make tuples of single values.
> Parenthesis are ways of controlling order of operation.
> They don't create tuples unless there's more than one value.

> Think of it like this:
> a TUple needs TWO elements or more.
> Solution:
> use lists.  They can contain single elements.

Don't know where you got that one from:


t = (1,)
type (t)



In fact, in a certain way, it's the comma which makes the tuple.
Brackets are only needed in some circs to disambiguate (eg in
parameter lists to functions)


t = 1,
type (t)


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


Re: [Tutor] stumped again adding bytes

2007-02-23 Thread Luke Paireepinart
shawn bright wrote:
> ok, i am good with what you have explained here,
> now i am on a similar problem.
>
> the data i need is in a condensed format. in other words, they are
> sending 2 values in three bytes.
>
> so if i have 3 values say a = 53, b = 13, and c = 31
>
> so value 1 is the first byte ( a ) and the first 4 bits of the second 
> byte (b)
> value 2 is the last 4 bits of byte (b) and byte (c)
Please try not to interchange your terms, it makes your questions confusing.
'so if i have 3 values say a = 53, b = 13, and c = 31'
Should be 'so if I have 3 bytes'
because immediately after, you talk about your extracted data as 'values.'
It's not too big of a deal, but it was confusing at first.
>
> so i believe i do shifting here. as in i do a
> (a << 4) * 32 + b
You need to read an article on bit manipulation.
I'll give you a summary of what you're trying to do.
given the byte
x = 1 1 0 0 0 1 1 0
If you want to extract just the four most significant bits, [1 1 0 0],
you shift the number TO THE RIGHT by 4.
x >> 4
will result in 4 shifts like so:
1 1 0 0 0 1 1 0 -> 1 1 0 0 0 1 1
1 1 0 0 0 1 1 -> 1 1 0 0 0 1
1 1 0 0 0 1 -> 1 1 0 0 0
1 1 0 0 0 -> 1 1 0 0
Which results in the number 0x0C or 12.
Now, since these are the MSB, you could shift back 4 places
x << 4
1 1 0 0 -> 1 1 0 0 0
1 1 0 0 0 -> 1 1 0 0 0 0
1 1 0 0 0 0 -> 1 1 0 0 0 0 0
1 1 0 0 0 0 0 -> 1 1 0 0 0 0 0 0

but I don't know if you want to do that or not.
and if you wanted to do that, you could just use a bitmask from the 
beginning.  see the next part.

Now as for the least significant bits:
recall that

1 1 0 0 0 1 0 0 & 0 0 0 0 1 1 1 1
will yeild
0 0 0 0 + whatever the last 4 bits are in the first item.

Hope that helps.
It's better if you take the time to really understand what is happening 
in all these cases, so you won't have to experiment with trial and error.
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionaries of Tuples of Strings

2007-02-23 Thread Luke Paireepinart
Adam Pridgen wrote:
> Hello,
>
> When I have a tuple with a single string in a dictionary entry and
> try to iterate over the tuple and it breaks the string into individual
> characters.  Is this supposed to be happening?
>
> This problem is a little tricky to explain so I have included the
> output and the corresponding example code.  In the example I have a
> dictionary with tuples of strings as the values.  If I have more than
> one tuple, I am ok and the value is not broken into individual
> characters (look at the "type="in the code below.  If I have only one
> string in the tuple value, then the string is broken into individual
> characters.  

That's because you can't make tuples of single values.
Parenthesis are ways of controlling order of operation.
They don't create tuples unless there's more than one value.
Example:
 >>> x = (('hello'))
 >>> type(x)

 >>> x = [['hello']]
 >>> type(x)


Think of it like this:
a TUple needs TWO elements or more.
Solution:
use lists.  They can contain single elements.

When you write
 >>> x = ('somestring')
you might think it's creating a single-value tuple, but it's not.
Consider this:
y = 5
z = 23
x = (y * (z + y) / y ** 3)

In this case you wouldn't expect these parenthesis to build tuples, 
would you?

Hope that helps somewhat,
-Luke

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


Re: [Tutor] stumped again adding bytes

2007-02-23 Thread shawn bright
ok, i am good with what you have explained here,
now i am on a similar problem.

the data i need is in a condensed format. in other words, they are
sending 2 values in three bytes.

so if i have 3 values say a = 53, b = 13, and c = 31

so value 1 is the first byte ( a ) and the first 4 bits of the second byte (b)
value 2 is the last 4 bits of byte (b) and byte (c)

so i believe i do shifting here. as in i do a
(a << 4) * 32 + b

but i am not getting what i think that i should be, and i think it's
because i am not getting rid of the bytes that i am not using.

i have looked at the struct module, but can't figgure out how to do
this type of thing with it.

thanks

shawn


On 2/21/07, Luke Paireepinart <[EMAIL PROTECTED]> wrote:
> shawn bright wrote:
> > oh, sorry, i meant how to get the 0x0A27 out of two bytes
> > a = 0x27 and b = 0x8A
> I don't see what the number 0x0A27 has to do with bytes 0x27 and 0x8A,
> but I'll assume you meant
> 0x0A for b.
> >
> > actually, in my script, i am not using the hex values at all, i have
> > these because they are examples in the documentation of a machine i am
> > talking to. i am actually using ord(a) and ord(b) to get digital
> > values of the numbers
> >
> > so, i guess a better question is how to get 2599 from the ord(a) and
> > ord(b), how do i put the two bytes together to make one number?
> Well, if you have the bytes originally, instead of ording them, hex them.
> so... given these bytes
> bytelist = [chr(0x27),chr(0x8A)]
> hexlist = []
> for item in bytelist:
>  hexlist.append(hex(item)[2:].zfill(2))
>
> print int('0x' + ''.join(hexlist) , 16)
>
> A less roundabout way to do this:
>
> given the number
> 0x0A,
> this is stored in the system the same as the number 10.
>  >>> 0x0A
> 10
> As you can see.
> So having the ord values is okay, because they're the same values as the
> hex of the bytes, just represented in a different base.
> Okay, now we'll assume that a byte is 8 bits.
> Because of this, we know that the number
> 0xFFEE
> is the same as
> (0xFF << 8) + 0xEE
> In other words, the higher byte is shifted over by 8 bits, and the other
> value is not shifted.
> This idea could easily be expanded to encompass byte strings of any length.
> Oh, and in the case of your example values,
>  >>> (0x0A << 8) + 0x27
> 2599
>
> Note that the + operator has higher (or the same?) precedence than the
> binary shift left.
> This means that the value 0x0A will be shifted by 8+0x27 times if the
> parenthesis are missing.
>
> Other equivalent operations:
>  >>> 0x0A * 256 + 0x27
> 2599
>  >>> 0x0A * 2**8 + 0x27
> 2599
>
> But like Kent said, you probably should use struct or something like that.
> Just in case you're interested, I'm sending this e-mail as well.
> HTH,
> -Luke
> >>
> >
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] miniwiki 1.3 BETA bugs

2007-02-23 Thread Barnaby Scott
Kirk Z. Bailey wrote:
> ok, let's post this again. last time went into purgatory instead of the list. 
> hmmm
> 
> I am working on updating miniwiki. the current beta code has rendering 
> problems with wikiwords and external sites under some circumstances. Here is 
> a link to the latest code:
> 
> http://www.tinylist.org/MW.txt
> 
> 
> 
> 
> 
> 
> 
> 
> Blessed Be!
>- Kirk Bailey
>  Largo FL USA
> 
> 
>  kniht  
> +-+ http://www.mylemonadestand.biz/ - play the lemonade game!
> | BOX | http://www.tinylist-org/ Freedom software
> +-+ In HER Service- http://www.pinellasintergroupsociety.org/
>  think  http://www.seaxtradusa.org/ - The Seax Wica Trad in the USA!
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


No idea if it has anything to do with your problem, but it struck me 
that the iswikiword() function (and processword() which seems to be a 
helper for it) could be replaced with one line, and it would be reliable!

def iswikiword(word):
 return bool(re.match('^([A-Z][a-z]+){2,}$', word))

Of course you need to import re, but that seems a small price to pay!

HTH

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


[Tutor] Dictionaries of Tuples of Strings

2007-02-23 Thread Adam Pridgen

Hello,

When I have a tuple with a single string in a dictionary entry and
try to iterate over the tuple and it breaks the string into individual
characters.  Is this supposed to be happening?

This problem is a little tricky to explain so I have included the
output and the corresponding example code.  In the example I have a
dictionary with tuples of strings as the values.  If I have more than
one tuple, I am ok and the value is not broken into individual
characters (look at the "type="in the code below.  If I have only one
string in the tuple value, then the string is broken into individual
characters.  Thanks again,

Adam.

Output:

name="years_of_newbness" type="xs:hexbinary"
name="years_of_newbness" type="xs:integer"

name="newb" type="x"
name="newb" type="s"
name="newb" type=":"
name="newb" type="t"
name="newb" type="r"
name="newb" type="i"
name="newb" type="n"
name="newb" type="g"

Example.py:

import sets

def Foo (elements=None):
   e_types = set()
   str = ""
   for k in elements:
   e_types.clear()
   for j in TYPES_PYTHON_TO_XML[k[1]]:# <-- Problem arises here
   # a tuple with a single string in dictionary is broken apart
   if j in e_types: continue
   str += CreateXMLElement(k[0], j)+"\n"
   e_types.add(j)
   print str

def CreateXMLComplex(name, elements):
   return XML_COMPLEX_STMNT%(name, elements)

def CreateXMLElement(name, type):
   return XML_ELEMENT_STMNT%(name, type)

XML_ELEMENT_STMNT = "name=\"%s\" type=\"%s\" "

TYPES_PYTHON_TO_XML = {
  'int':('xs:hexbinary','xs:integer'),
  'str':("xs:string")
  }
Foo([("years_of_newbness", "int")]) # <-- Works, more than one element
in the tuple
Foo([('newb', 'str')])# <-- Fails, only one element in the tuple
import sets

def Foo (elements=None):
e_types = set()
str = ""
for k in elements:
e_types.clear()
for j in TYPES_PYTHON_TO_XML[k[1]]:# <-- Problem arises here 
# a tuple with a single string in dictionary is broken apart
if j in e_types: continue 
str += CreateXMLElement(k[0], j)+"\n"
e_types.add(j)
print str

def CreateXMLComplex(name, elements):
return XML_COMPLEX_STMNT%(name, elements)

def CreateXMLElement(name, type):
return XML_ELEMENT_STMNT%(name, type)

XML_ELEMENT_STMNT = "name=\"%s\" type=\"%s\" "

TYPES_PYTHON_TO_XML = {
   'int':('xs:hexbinary','xs:integer'),
   'str':("xs:string")
   }
Foo([("years_of_newbness", "int")]) # <-- Works, more than one element in the tuple
Foo([('newb', 'str')])# <-- Fails, only one element in the tuple___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionaries and memory handling

2007-02-23 Thread Bill Campbell
On Fri, Feb 23, 2007, Alan Gauld wrote:
>"Bill Campbell" <[EMAIL PROTECTED]> wrote
>
>>>It seems that an SQL database would probably be the way to go, but I
>>>am a bit concerned about speed issues (even though running time is
>> ...
>> You would probably be better off using one of the hash databases,
>> Berkeley, gdbm, etc. (see the anydbm documentation).  These can
>> be treated exactly like dictionaries in python, and are probably
>> orders of magnitude faster than using an SQL database.
>
>I'm glad Bill suggested this because I'd forgotten about them 
>entirely!
>But while they wont literally be "orders of magnitude" faster - the
>disk I/O subsystem is usually the main limiter here -  they will be
>several factors faster, in fact many SQL databases use the dbm
>database under the hood.

While the disk subsystem is going to be a factor, the overhead
communicating with the SQL server, parsing the queries, etc. will be far
greater than calculating location of the record using the hashed key.

FWIW: I've found that the size of Berkeley DB btree files can be
significantly less than the Berkeley hash files.

I would really like to see somebody come up with a good alternative to the
Berkeley DB stuff from sleepcat.  The source code is the most godawfull
mess if #ifn*defs I've ever seen, with frequent API even in minor release
levels.  Take a look at the bdb source in python or perl if you want to see
what I'm talking about.

Bill
--
INTERNET:   [EMAIL PROTECTED]  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:(206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

``the purpose of government is to reign in the rights of the people''
-Bill Clinton during an interview on MTV in 1993
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionaries and memory handling

2007-02-23 Thread Alan Gauld
"Bill Campbell" <[EMAIL PROTECTED]> wrote

>>It seems that an SQL database would probably be the way to go, but I
>>am a bit concerned about speed issues (even though running time is
> ...
> You would probably be better off using one of the hash databases,
> Berkeley, gdbm, etc. (see the anydbm documentation).  These can
> be treated exactly like dictionaries in python, and are probably
> orders of magnitude faster than using an SQL database.

I'm glad Bill suggested this because I'd forgotten about them 
entirely!
But while they wont literally be "orders of magnitude" faster - the
disk I/O subsystem is usually the main limiter here -  they will be
several factors faster, in fact many SQL databases use the dbm
database under the hood.

It's years since I used dbm, I must have a play - just for old
times sake! :-)

Alan G. 


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


[Tutor] Programming the behavior of a set of domino

2007-02-23 Thread Chung-hong Chan
Hello,

I am a newbie in computer programming and I am also not a native
English Speaker. I love to play domino and I would like to program a
simple domino game in python. Also a good opportunity for me to learn
some computer programming.
I need some help in my code which programming the behaviors of a set of domino.
Here is the code, generally a modification of the code from the deck
of card example in How to Think like a Computer Scientist.

#!/usr/bin/python
class domino:
def __init__(self,a_end,b_end):
self.a_end=a_end
self.b_end=b_end
def __str__(self):
return ("["+str(self.a_end)+","+str(self.b_end)+"]")
def __cmp__(self,other):
if self.a_end==other.b_end and self.b_end==other.a_end:
return 0
return 1

class deck:
def __init__(self,set_type):
self.dominoes = []
self.set_type = set_type
for a_end in range(self.set_type+1):
for b_end in range(self.set_type+1):
self.dominoes.append(domino(a_end,b_end))
def print_deck(self):
for domino in self.dominoes:
print domino
def deck_len(self):
print len(self.dominoes)


newdomino = deck(12)
newdomino.print_deck()
newdomino.deck_len()

if domino(1,2)==domino(2,2):
print "yes"
else:
print "no"

each piece of domino have a_end and b_end. domino (1,2) and
domino(2,1) is the same and thus one of them should be removed. Now,
deck(12) will return 169 dominoes while the expected number of
dominoes is 91. Even I wrote a __cmp__ method for domino, list
membership (i.e. x in list) is not working because they are not a
exact duplicates.
Can anyone shed me some light to solve this problem?
Thank You.

Regards,
CH


-- 
"The scientists of today think deeply instead of clearly. One must be
sane to think clearly, but one can think deeply and be quite insane."
Nikola Tesla
http://www.macgrass.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionaries and memory handling

2007-02-23 Thread Bill Campbell
On Fri, Feb 23, 2007, =?ISO-8859-1?Q? Arild_B._N=E6ss ?= wrote:
>Hi,
>
>I'm working on a python script for a task in statistical language  
>processing. Briefly put it all boils down to counting different  
>things in very large text files, doing simple computations on these  
>counts and storing the results. I have been using python's dictionary  
>type as my basic data structure of storing the counts. This has been  
>a nice and simple solution, but turns out to be a bad idea in the  
>long run, since the dictionaries become _very_ large, and create  
>MemoryErrors when I try to run my script on texts of a certain size.
>
>It seems that an SQL database would probably be the way to go, but I  
>am a bit concerned about speed issues (even though running time is  
>not all that crucial here). In any case it would probably take me a  
>while to get a database up and running and I need to hand in some  
>preliminary results pretty soon, so for now I think I'll postpone the  
>SQL and try to tweak my current script to be able to run it on  
>slightly longer texts than it can handle now.

You would probably be better off using one of the hash databases,
Berkeley, gdbm, etc. (see the anydbm documentation).  These can
be treated exactly like dictionaries in python, and are probably
orders of magnitude faster than using an SQL database.

Bill
--
INTERNET:   [EMAIL PROTECTED]  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:(206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

``Rightful liberty is unobstructed action according to our will within
limits drawn around us by the equal rights of others. I do not add 'within
the limits of the law' because law is often but the tyrant's will, and
always so when it violates the rights of the individual.''
-Thomas Jefferson
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] dictionaries and memory handling

2007-02-23 Thread Arild B. Næss
Hi,

I'm working on a python script for a task in statistical language  
processing. Briefly put it all boils down to counting different  
things in very large text files, doing simple computations on these  
counts and storing the results. I have been using python's dictionary  
type as my basic data structure of storing the counts. This has been  
a nice and simple solution, but turns out to be a bad idea in the  
long run, since the dictionaries become _very_ large, and create  
MemoryErrors when I try to run my script on texts of a certain size.

It seems that an SQL database would probably be the way to go, but I  
am a bit concerned about speed issues (even though running time is  
not all that crucial here). In any case it would probably take me a  
while to get a database up and running and I need to hand in some  
preliminary results pretty soon, so for now I think I'll postpone the  
SQL and try to tweak my current script to be able to run it on  
slightly longer texts than it can handle now.

So, enough beating around the bush, my questions are:

- Will the dictionaries take up less memory if I use numbers rather  
than words as keys (i.e. will {3:45, 6:77, 9:33} consume less memory  
than {"eloquent":45, "helpless":77, "samaritan":33} )? And if so:  
Slightly less, or substantially less memory?

- What are common methods to monitor the memory usage of a script?  
Can I add a snippet to the code that prints out how many MBs of  
memory a certain dictionary takes up at that particular time?

regards,
Arild Næss
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How many loops does "break" jump out of?

2007-02-23 Thread Chuck Coker
Bob,

Watch your code blocks to make sure you don't change your logic
inadvertently. The code starting with "if (test_2)" and continuing to
the end of the snippet is inside the perpetual for loop which is inside
the "if (test_1)" condition.

Chuck



Bob Gailer wrote:

> [EMAIL PROTECTED] wrote:
>
>> Am trying to convert a C program with a GOTO in it to Python and was 
>> wondering
>> how many loops a Python "break" jumps out of. Here is the C pseudo code
>>
>> if (test_1) {
>> for (;;) {
>> if (test_2) {
>> do_stuff();
>> } else if (test_2) {
>> for (ip=m1+m2+1;ip<=m;ip++) {
>> if (test_3) {
>> do_more_stuff();
>> if (test_4)
>> goto one;
>> }
>> }
>> for (i=m1+1;i<=m1+m2;i++)
>> do_even_more_stuff();
>>
>> do_yet_more_stuff();
>> }
>>
>> do_final_stuff();
>>
>> one: continue_program();
>
> I'd put this code in a function, replace the goto one with return, and
> put a call to the function in place of the code.
>
> def tests():
> if test_1:
> etc etc
> if test_4: return
>
> Some may take issue with that. You can, as Alan says, restructure the
> code, or use intermediate variables.

-- 
==
Chuck Coker, Software Developer[EMAIL PROTECTED]
Tyrell Software Corporation  http://www.tyrell.com
Office: +1 949 458 1911 x 203Cell: +1 714 326 5939
==

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


Re: [Tutor] DICOM Header

2007-02-23 Thread Bill Sconce
On Thu, 22 Feb 2007 13:51:35 -0700
"Andrew Liimatta" <[EMAIL PROTECTED]> wrote:

> I have a directory that is filled with DICOM files that I obtained
> by using the Offis DICOM tool kit.

Ah.  The light dawns.  I should offer to communicate with you off-list,
and report back here after we've solved the problem.  I have DICOM files
here, and it sounds like an interesting and useful thing to be able to
do (inspect DICOM files with Python).  The next step is to talk more
specifically about what it is you want to do, which will likely require
more discussion about DICOM than we should burden the list with.

Let's say I were able to send you a snippet of code that returns a
list containing the values of SourceApplicationEntityTitle fields
(say) for each DICOM file in your directory.  Am I on the right track?

Feel free to write back to me off-list.

-Bill




> The dictionary file I have is not included in the DICOM file. I have
> a flat file that has all of the DICOM fields defined as a python
> dictionary.  [...] 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] miniwiki 1.3 BETA bugs

2007-02-23 Thread Luke Paireepinart
Kirk Z. Bailey wrote:
> ok, let's post this again. last time went into purgatory instead of the list. 
> hmmm
>
> I am working on updating miniwiki. the current beta code has rendering 
> problems with wikiwords and external sites under some circumstances. 
What circumstances are these, exactly?
That's pretty vague.
And what are the rendering problems?
> Here is a link to the latest code:
>
> http://www.tinylist.org/MW.txt
>
>
>
>
>
>
>
>
> Blessed Be!
>- Kirk Bailey
>  Largo FL USA
>
> 
>  kniht  
> +-+ http://www.mylemonadestand.biz/ - play the lemonade game!
> | BOX | http://www.tinylist-org/ Freedom software
> +-+ In HER Service- http://www.pinellasintergroupsociety.org/
>  think  http://www.seaxtradusa.org/ - The Seax Wica Trad in the USA!
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   

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


[Tutor] miniwiki 1.3 BETA bugs

2007-02-23 Thread Kirk Z. Bailey
ok, let's post this again. last time went into purgatory instead of the list. 
hmmm

I am working on updating miniwiki. the current beta code has rendering problems 
with wikiwords and external sites under some circumstances. Here is a link to 
the latest code:

http://www.tinylist.org/MW.txt








Blessed Be!
   - Kirk Bailey
 Largo FL USA


 kniht  
+-+ http://www.mylemonadestand.biz/ - play the lemonade game!
| BOX | http://www.tinylist-org/ Freedom software
+-+ In HER Service- http://www.pinellasintergroupsociety.org/
 think  http://www.seaxtradusa.org/ - The Seax Wica Trad in the USA!

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


Re: [Tutor] index swap?

2007-02-23 Thread Kent Johnson
Switanek, Nick wrote:
> Hi,
> 
>  
> 
> I’m trying to subset a large dataset (too many rows for Excel, currently 
> too ragged for Access), and I am mystified by the behavior of a 
> seemingly simple script I’ve written. Please help me understand what I’m 
> overlooking.
> 
> data = file(inpath).readlines()
> data = [line.rstrip() for line in data]
> data = [line.split('\t') for line in data]

This could be written more simply using a single list comprehension:
data = [ line.rstrip().split('\t') for line in open(inpath) ]

> # I wish to select the elements of a list by using a list of indices:
> 
> indices = [0, 1, 28, 29]   # for example 
> dataOut = []
> 
> for row in data:
> rowOut = []
> for i in indices:
> rowOut.append(row[i])
> dataOut.append(rowOut)

Again I would write this with nested list comps:
dataOut = [ [ row[i] for i in indices ] for row in data ]

> The problem is that while the first list in the list of lists ‘dataOut’, 
> i.e. my header row, has taken the headers with the appropriate indices 
> from the index list, all other rows swap the elements with indices 28 
> and 29. If I include just one of the two indices 28 or 29, the problem 
> remains: save for the header list, I get element 29 where I want 28, and 
> element 29 when I want element 28. This swapping doesn’t occur for any 
> other indices that I’ve tested.

Are you sure the headers and data are in the order you think they are? I 
suspect that your data is not what you think it is. What do you get if 
you try
for row in data[:3]:
   print repr(row)
   print row[28]
   print row[29]
   print

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


Re: [Tutor] Managing XML in Python

2007-02-23 Thread Kent Johnson
Ketan Maheshwari wrote:
> Hi:
> I have to manage XML files through python. The activities include, 
> create, update and retrieve information from the XML files.
> 
> I would be thankful for pointers to tutorials, APIs and suggestions.

Take a look at the ElementTree module. In Python 2.5 it is built in:
http://docs.python.org/lib/module-xml.etree.ElementTree.html

For older Pythons, and for more extensive docs, see
http://effbot.org/zone/element.htm

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


[Tutor] index swap?

2007-02-23 Thread Switanek, Nick
Hi,

 

I'm trying to subset a large dataset (too many rows for Excel, currently
too ragged for Access), and I am mystified by the behavior of a
seemingly simple script I've written. Please help me understand what I'm
overlooking.

 

data = file(inpath).readlines()

data = [line.rstrip() for line in data]

data = [line.split('\t') for line in data]

 

# I wish to select the elements of a list by using a list of indices:

indices = [0, 1, 28, 29]   # for example

 

dataOut = []

for row in data:

rowOut = []

for i in indices:

rowOut.append(row[i])

dataOut.append(rowOut)

 

 

The problem is that while the first list in the list of lists 'dataOut',
i.e. my header row, has taken the headers with the appropriate indices
from the index list, all other rows swap the elements with indices 28
and 29. If I include just one of the two indices 28 or 29, the problem
remains: save for the header list, I get element 29 where I want 28, and
element 29 when I want element 28. This swapping doesn't occur for any
other indices that I've tested. 

 

Running the same code interactively doesn't seem to result in the index
swap. I'm sure I'm overlooking something basic, and I'd be grateful for
your help pointing it out.

 

 

Many thanks in advance,

Nick

 

 

 

 

 

 

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


Re: [Tutor] Add metadata to a dir of files.

2007-02-23 Thread Tim Golden
Mark Bystry wrote:
> Ok, Tim. I believe you're right. If the vbscript is working then I'll 
> continue to use it and expand 
> on it. I'll only be using this on my WinXP box anyway. I just didn't want to 
> offend anyone in this 
> mailing list with vbscript code. I'm really trying to learn some python 
> basics but I'm no programmer.

Don't worry; you won't offend many (or any) people here. We're
really quite friendly, are we're not such bigots as to believe
that Only Python solutions are acceptable. The only danger is
in not finding someone who can help. I assume there are VBS
forums somewhere. (Or should that be fora? :)

Good luck with it, and feel free to come back if you still need
help.

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


Re: [Tutor] Add metadata to a dir of files.

2007-02-23 Thread Mark Bystry
Ok, Tim. I believe you're right. If the vbscript is working then I'll continue 
to use it and expand 
on it. I'll only be using this on my WinXP box anyway. I just didn't want to 
offend anyone in this 
mailing list with vbscript code. I'm really trying to learn some python basics 
but I'm no programmer.

Thanks everyone for your help.

Mark.

Tim Golden wrote the following on 2/22/2007 4:06 PM:
> Tim Golden wrote:
>> Slightly bizarrely, it works fine for me on a different
>> computer (my laptop). Both are Win2K. The only help I
>> could find on the error code suggested a permission issue,
>> which isn't likely. That said, I have experienced a few
>> funnies with the Python script writing the new Category
>> open in one window, and trying to use Explorer to update
>> the Summary info in another.
>>
>> Might be worth making sure nothing else is blocking, and
>> giving it another go. I'll try it on a random collection
>> of files to see if it runs...
> 
> No joy. It's falling over again with another eight-byte
> twos-complement error code. Frankly, if your VBS version
> runs, use it! (Especially if this is just one of those
> one-off things).
> 
> TJG
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Managing XML in Python

2007-02-23 Thread Ketan Maheshwari
Hi:
I have to manage XML files through python. The activities include, 
create, update and retrieve information from the XML files.

I would be thankful for pointers to tutorials, APIs and suggestions.

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


Re: [Tutor] Running an exe from Python

2007-02-23 Thread Alan Gauld

"Rikard Bosnjakovic" <[EMAIL PROTECTED]> wrote

>> How can I get python to display
>> the results in the interactive window or what is the right way to 
>> do this.
>
> Use os.popen:

As Rikard, Richard and Hugo have pointed out there are
numerous ways to do this in Python.

The officially sanctioned way nowadays is to use the subprocess
module. It supercedes all tthe previous methods being both more
powerful, more flexible and fairly easy to use.

All the techniques are discussed in my Using the OS topic in
my tutorial.

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