Re: [Tutor] the and command

2007-08-24 Thread Alan Gauld

"max baseman" <[EMAIL PROTECTED]> wrote
> im checking if a number is in all 5 of the other lists and when
> i use the and command it seems to just be checking if it's in a 
> least
> one of the others,


> for num in l2 and l3 and l4 and l5 and l6: # here seems to be the

Try:

if num in I2 and num in I3 and num in I4 and num in I5 and num in I6:

In your case you are 'and'ing the lists which is a boolean expression
and because of how Python does short circuit evaluation it returns
the last list

>>> a = [1,2]
>>> b = [3,4]
>>> a and b
[3, 4]

so

for n in a and b:

is the same as

for n in b:

which iterates over b...

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] the and command

2007-08-24 Thread max baseman
thanks much you really helped me if anyone wants here is the program:

n2=2
n3=3
n4=4
n5=5
n6=6
n7=7
l2=[]
l3=[]
l4=[]
l5=[]
l6=[]
l7=[]
while n2 < 1000:
 l2.append(n2)
 n2=n2+2
while n3 < 1000:
 l3.append(n3)
 n3=n3+3
while n4 < 1000:
 l4.append(n4)
 n4=n4+4
while n5 < 1000:
 l5.append(n5)
 n5=n5+5
while n6 < 1000:
 l6.append(n6)
 n6=n6+6
while n7<1000:
 l7.append(n7)
 n7=n7+7
possible=[]
for num in l2:
 if num in l3 and num in l4 and num in l5 and num in l6:
 possible.append(num)
for a in possible:
 if a+1 in l7:
 print a+1



On Aug 24, 2007, at 1:25 AM, Alan Gauld wrote:

>
> "max baseman" <[EMAIL PROTECTED]> wrote
>> im checking if a number is in all 5 of the other lists and when
>> i use the and command it seems to just be checking if it's in a
>> least
>> one of the others,
>
>
>> for num in l2 and l3 and l4 and l5 and l6: # here seems to be the
>
> Try:
>
> if num in I2 and num in I3 and num in I4 and num in I5 and num in I6:
>
> In your case you are 'and'ing the lists which is a boolean expression
> and because of how Python does short circuit evaluation it returns
> the last list
>
 a = [1,2]
 b = [3,4]
 a and b
> [3, 4]
>
> so
>
> for n in a and b:
>
> is the same as
>
> for n in b:
>
> which iterates over b...
>
> 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

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


Re: [Tutor] the and command

2007-08-24 Thread Kent Johnson
max baseman wrote:
> thanks much you really helped me if anyone wants here is the program:

Hmmm...this is quite wordy. Some suggestions below:
> 
> n2=2
> n3=3
> n4=4
> n5=5
> n6=6
> n7=7
> l2=[]
> l3=[]
> l4=[]
> l5=[]
> l6=[]
> l7=[]
> while n2 < 1000:
>  l2.append(n2)
>  n2=n2+2

This can be written
l2 = range(2, 1000, 2)

> while n3 < 1000:
>  l3.append(n3)
>  n3=n3+3
> while n4 < 1000:
>  l4.append(n4)
>  n4=n4+4
> while n5 < 1000:
>  l5.append(n5)
>  n5=n5+5
> while n6 < 1000:
>  l6.append(n6)
>  n6=n6+6
> while n7<1000:
>  l7.append(n7)
>  n7=n7+7
> possible=[]
> for num in l2:
>  if num in l3 and num in l4 and num in l5 and num in l6:
>  possible.append(num)

Testing for membership is better done with sets or dicts than lists. In 
this case you want the intersection of l2,...,l6. Sets support 
intersection directly. Also l2 and l3 are redundant; any number in l6 
will also be in l2 and l3. So possible can be created as a set like this:

possible = set(xrange(4, 1000, 4)).intersection(xrange(5, 1000, 5)) \
 .intersection(xrange(6, 1000, 6))

> for a in possible:
>  if a+1 in l7:
>  print a+1

Here you are checking if a is divisible by 7. You could do it directly 
instead of creating a helper:

for a in possible:
 if (a+1) % 7 == 0:
 print a+1

Or you could apply a little more number theory and realize that to be a 
multiple of 4, 5 and 6 it is necessary and sufficient to be a multiple 
of 60 and write the whole thing in one loop:

for a in xrange(60, 1000, 60):
 if (a+1) % 7 == 0:
 print a+1

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


[Tutor] Off Topic: xrange, WAS: Re: the and command

2007-08-24 Thread Alan Gauld
"Kent Johnson" <[EMAIL PROTECTED]> wrote

> possible = set(xrange(4, 1000, 4)).intersection(xrange(5, 1000, 5)) 
> \
> .intersection(xrange(6, 1000, 6))
>

Kent,

I've noticed in a few of your replie recemntly you have been using
xrange rather than range. I was under the impression that since
iterators were introduced that xrange was more or less just an
alias for range. Your usage suggests that my understanding is
wrong?

However, even in its original incarnation I would not have used it
here since I thought its main advantage was in loops where it
(like a geneator) yielded values one by one to save memory.
In this case aren't you generating the full set in each case?
Or at least in the first case, the set()?

I notice that help() still differentiates between the two,
and indeed that xrange purports to be a type rather than
a function.

I suspect I'm missing something! :-)

Alan G 


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


Re: [Tutor] Converting code to string

2007-08-24 Thread Bernard Lebel
Actually, regarding inspect.getsource() that raised IOErrors:
Running it from imported module actually works!


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


Re: [Tutor] Off Topic: xrange, WAS: Re: the and command

2007-08-24 Thread Kent Johnson
Alan Gauld wrote:
> "Kent Johnson" <[EMAIL PROTECTED]> wrote
> 
>> possible = set(xrange(4, 1000, 4)).intersection(xrange(5, 1000, 5)) 
>> \
>> .intersection(xrange(6, 1000, 6))
>>
> 
> Kent,
> 
> I've noticed in a few of your replie recemntly you have been using
> xrange rather than range. I was under the impression that since
> iterators were introduced that xrange was more or less just an
> alias for range. Your usage suggests that my understanding is
> wrong?

Yes, you misunderstand. range() still creates a list, xrange() returns a 
iterator. In Python 3000 range() will return an iterator and xrange() 
will go away.

In [3]: type(range(1000))
Out[3]: 
In [4]: type(xrange(1000))
Out[4]: 

> However, even in its original incarnation I would not have used it
> here since I thought its main advantage was in loops where it
> (like a geneator) yielded values one by one to save memory.
> In this case aren't you generating the full set in each case?
> Or at least in the first case, the set()?

I generate the full set but using xrange() avoids creating an 
intermediate list. set() is happy to have an iterable argument, it 
doesn't need a list. There is an implicit loop; the set constructor must 
iterate over its argument. There is a modest performance benefit to 
using xrange():

src $ python -m timeit "set(range(1000))"
1 loops, best of 3: 99.8 usec per loop
src $ python -m timeit "set(xrange(1000))"
1 loops, best of 3: 86.7 usec per loop

Of course in most cases 13 usec is not of any consequence. In fact in my 
own code I usually use range().

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


Re: [Tutor] Converting code to string

2007-08-24 Thread Bernard Lebel
okay here "simple" examples about why I have to define callbacks as
strings instead of code.

In XSI, one of the GUI objects that you can create is called a "custom
property". A custom property is basically a floating window in which
there are widgets. Custom properties can define a layout or not.

Custom properties that do not define a layout display a bunch of
simple widgets (text fields, sliders for scalar values, checkboxes,
etc), vertically on top of each other.

Custom properties that define a layout offer a lot more interesting
widgets: buttons, tabs, combo boxes, radio buttons, labels, groups,
etc. To interactive widgets, callbacks can be attached. So when a
button is clicked or a combo box changed, code can be ran.


There are two implementations for custom property layouts.

1- property plugins: the entire property is defined in a plugin file.
Here the programmer can put any amount of widgets and callbacks he
wants. However, the number of such items is constant, one cannot
dynamically add or remove elements from a property created in that
fashion. (well, perhaps it is possible, but I don't know how).

When the XSI application starts, the plugin is loaded. In scripts, the
property can be instantiated and inspected.

The great benefit of this approach is that the property's layout and
logic are persistable. Since those are defined in a plugin, if the
plugin is always found, then the property will keep its layout and
logic, even if the document is closed and reopen.

Here is an example of such a plugin:


# Load plugin in XSI

def XSILoadPlugin( in_reg ):
in_reg.Author = "Bernard Lebel"
in_reg.Name = "plugindemo"
in_reg.Major = 1
in_reg.Minor = 1
in_reg.RegisterProperty( "propertyplugindemo" )
return True

# Define property

def propertyplugindemo_Define( io_Context ):
""" Add parameters """
oProp = io_Context.source
oProp.addparameter3( 'myparameter', 8, '' )

def propertyplugindemo_DefineLayout( io_Context ):
""" Skip layout creation. We'll do it at inspection time. """
pass

def propertyplugindemo_OnInit():
""" Called when the property is inspected
(brought up to the screen for the user to use it) """
oProp = PPG.Inspected(0)

# Create property layout
oLayout = PPG.PPGLayout
oLayout.Clear()

oLayout.additem( 'myparameter', 'myparameter' ) # add "myparameter text 
field"
oLayout.addbutton( 'myButton' ) # add "myButton" button

PPG.Refresh()

# Callbacks for widgets
def propertyplugindemo_myButton_OnClicked():
print 'hello world'


2- on-the-fly logic: instead of creating a plugin, the programmer can
create a custom property along with layout and logic entirely at
execution time. While this prevents the property layout and logic from
being persisted, it allows the programmer to define dynamically how
many widgets and callback he wants.

The problem with this approach is that it I believe it was not
designed with Python in mind, but rather JScript. The callbacks
defined in "on-the-fly" context, for some reason, must be written as
strings and then injected into the property's logic. JScript has the
toString() method, which converts easily code blocks into strings.

The following Pythoin code works well. Functions are written directly
as strings, so no problem. It does exactly the same property as the
example above, except that it is being done "on-the-fly" instead of
through a plugin.


# Instantiate the Applicaiton object,
# for running command in the host application
xsi = Application

# Define callback functions
sOnInit = """def OnInit():
   pass"""

sMyButtonOnClicked = """def myButton_OnClicked():
   print 'hello world'"""

# Create plain custom property
oProperty = xsi.activesceneroot.addproperty( 'CustomProperty', False )

# Add parameters
oParameter = oProperty.addparameter3( 'myparameter', 8, '' )

# Get property layout
oLayout = oProperty.PPGLayout
oLayout.Clear()

# Set the layout environment
oLayout.Language = 'Python'

# Inject logic into the layout.
# Join all functions defined in strings.
oLayout.Logic = '\n'.join( [sOnInit, sMyButtonOnClicked] )

# Create buttons
oLayout.additem( oParameter.scriptname, oParameter.scriptname )
oLayout.addbutton( 'myButton' )

# Inspect the property
xsi.inspectobj( oProperty )



Now back to the actual problem.

In the task I'm currently having, I have to dynamically create a
certain number of layout elements along its logic. The number of
elements to create changes from one execution to the next, as it is
driven by the user input. Since properpty plugins do not support such
dynamic creation, my only solution is with the "on-the-fly" approach.

Now what I'd like to do is to create "real" functions, not strings,
and convert them into strings for logic injection.



Thanks!
Bernard
___
Tutor maillist  -  Tutor@p

Re: [Tutor] Converting code to string

2007-08-24 Thread Kent Johnson
Bernard Lebel wrote:
> In the task I'm currently having, I have to dynamically create a
> certain number of layout elements along its logic. The number of
> elements to create changes from one execution to the next, as it is
> driven by the user input. Since properpty plugins do not support such
> dynamic creation, my only solution is with the "on-the-fly" approach.
> 
> Now what I'd like to do is to create "real" functions, not strings,
> and convert them into strings for logic injection.

I think the inspect module is as good as you are going to get and it is 
just looking up the source code for a function and giving it back to you 
so it won't work with any kind of dynamic function, for example a 
function created inside a closure would not have a useful string 
representation in source.

Maybe you should look instead at flexible ways of creating the strings 
you need, some kind of template language. There are some simple ones in 
the Python Cookbook:
http://aspn.activestate.com/ASPN/search?query=template&x=0&y=0§ion=PYTHONCKBK&type=Subsection
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52305

and quite a few more that have been developed for Web server use:
http://wiki.python.org/moin/Templating

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


[Tutor] Help Request: Nested While commands

2007-08-24 Thread Paul W Peterson

Greeting!
I'm learning Python through the book "Python Programming, Second Edition
for the absolute beginner" by Michael Dawson. In it, he has the program
"Guess my number" (code pasted below). His challenge is to modify the
code so that there are only a limited number of attempts before the
program exits with a chastising message. 

Try as I may, I cannot seem to get the syntax correct for nested while
loops.  I was able to do it with two separate if statements, but this
seems very unelegant to me.  Could you provide a way to achieve this
using nested while statements, or suggest a better use of the ifs? 

Also, while asking for help from this forum: for short pieces of code
such as these, is it appropriate to enter them as inline text, or is it
preferred to have them as attachments? I presume for long pieces of code
the latter applies. 

Thank you

Paul Peterson
Ellicott, Colorado
The Technological Capital of Mid Central Eastern El Paso County,
Colorado. 





# Guess My Number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money

import random  

print "\tWelcome to 'Guess My Number'!"
print "\nI'm thinking of a number between 1 and 100." 
print "Try to guess it in as few attempts as possible.\n"

# set the initial values
the_number = random.randrange(100) + 1
guess = int(raw_input("Take a guess: "))
tries = 1

# guessing loop
while (guess != the_number):
if tries < 5:
if (guess > the_number):
print "Lower..."
else:
print "Higher..."

guess = int(raw_input("Take a guess: "))
tries += 1
else:
break

if tries < 5:
print "You guessed it!  The number was", the_number
print "And it only took you", tries, "tries!\n"
else:
print "You have exceeded your attempts."
  
raw_input("\n\nPress the enter key to exit.")
# Guess My Number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money

import random  

print "\tWelcome to 'Guess My Number'!"
print "\nI'm thinking of a number between 1 and 100." 
print "Try to guess it in as few attempts as possible.\n"

# set the initial values
the_number = random.randrange(100) + 1
guess = int(raw_input("Take a guess: "))
tries = 1

# guessing loop
while (guess != the_number):
if (guess > the_number):
print "Lower..."
else:
print "Higher..."

guess = int(raw_input("Take a guess: "))
tries += 1

print "You guessed it!  The number was", the_number
print "And it only took you", tries, "tries!\n"
  
raw_input("\n\nPress the enter key to exit.")
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] using in over several entities

2007-08-24 Thread Kent Johnson
Tino Dai wrote:
> Hi there,
> 
> I am wondering about a short cut to doing this. Let's say that we 
> have an array:
> 
> dbs= ['oracle','mysql','postgres','infomix','access']
> 
> and we wanted to do this:
> 
> if 'oracle' in dbs or 'mysql' in dbs or 'bdb' in dbs:
><... do something ...>
> 
> Is there a short way or writing this? Something like
> ('oracle','mysql','bdb') in dbs

I don't think there is a shortcut with lists. You could write
any(db in dbs for db in ('oracle','mysql','bdb'))

which at least lets you use a list for the targets, or
if [ db for db in ('oracle','mysql','bdb') if db in dbs ]:

With sets you can write
dbs= set(['oracle','mysql','postgres','infomix','access'])
if dbs.intersection(('oracle','mysql','bdb')):

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


Re: [Tutor] HOWTO: adding to sys.path the simplest way.

2007-08-24 Thread Tim Johnson
On Thursday 23 August 2007, Kent Johnson wrote:
 
> > I would welcome some opinions on this matter.
>
> Make a file called mylibraries.pth with contents
> /path/to/mylibraries
 Aha! User-defined .pth file is recognized by python
> Put the file in your site-packages folder (I don't know wherethat is for
> you).
  On *nix systems, I think it is generally 
   var/lib/python/site-packages
> Updating Python will still require copying the .pth file to the new
> site-packages folder but no editing.
 Great!
Thanks Kent
Tim 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] using in over several entities

2007-08-24 Thread Tino Dai
Hi there,

I am wondering about a short cut to doing this. Let's say that we have
an array:

dbs= ['oracle','mysql','postgres','infomix','access']

and we wanted to do this:

if 'oracle' in dbs or 'mysql' in dbs or 'bdb' in dbs:
   <... do something ...>

Is there a short way or writing this? Something like
('oracle','mysql','bdb') in dbs

I do see that the the conjunction can be problematic, and I do see that can
write a short function to get this working. But before I do that, I wanted
to see that there was nothing in Python that already did that.

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


Re: [Tutor] HOWTO: adding to sys.path the simplest way.

2007-08-24 Thread Tim Johnson
On Friday 24 August 2007, Tim Johnson wrote:
> On Thursday 23 August 2007, Kent Johnson wrote:
> > > I would welcome some opinions on this matter.
> >
> > Make a file called mylibraries.pth with contents
> > /path/to/mylibraries
>
>  Aha! User-defined .pth file is recognized by python
>
> > Put the file in your site-packages folder (I don't know wherethat is for
> > you).
>
>   On *nix systems, I think it is generally
>var/lib/python/site-packages
  Oops! Meant to say /usr/lib/python...
  sorry.
tim


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


Re: [Tutor] using in over several entities

2007-08-24 Thread Chris Calloway
Tino Dai wrote:
> I am wondering about a short cut to doing this. Let's say that we 
> have an array:
> 
> dbs= ['oracle','mysql','postgres','infomix','access']
> 
> and we wanted to do this:
> 
> if 'oracle' in dbs or 'mysql' in dbs or 'bdb' in dbs:
><... do something ...>
> 
> Is there a short way or writing this? Something like
> ('oracle','mysql','bdb') in dbs

Sets to the rescue. Set intersection specifically:

 >>> dbs = set(['oracle','mysql','postgres','infomix','access'])
 >>> mine = set(['oracle','mysql','bdb'])
 >>> dbs & mine
set(['oracle', 'mysql'])
 >>> if dbs & mine:
... print 'doing something'
...
doing something
 >>>

This also has the advantage of returning to you an object of exactly 
what elements in mine were in dbs. And difference:

 >>> dbs - mine
set(['access', 'infomix', 'postgres'])
 >>>

will show you which elements of mine were not in dbs.

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599



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


Re: [Tutor] the and command

2007-08-24 Thread Mike Hansen
 

> -Original Message-
> 
...
> > for num in l2:
> >  if num in l3 and num in l4 and num in l5 and num in l6:
> >  possible.append(num)

Yikes! Glancing at the code, I was reading l3, l4, l5, l6 as the numbers
13, 14, 15, 16..(Thirteen, Fourteen, Fifteen, Sixteen). I'd avoid using
variables named like that since the lowercase L looks like a one (l, 1)
in many fonts.

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


Re: [Tutor] Help Request: Nested While commands

2007-08-24 Thread Alan Gauld

"Paul W Peterson" <[EMAIL PROTECTED]> wrote 

> "Guess my number" (code pasted below). His challenge is to modify the
> code so that there are only a limited number of attempts before the
> program exits with a chastising message. 
> 
> Try as I may, I cannot seem to get the syntax correct for nested while
> loops.  

I wouldn't use a nested loop for that but an if/break at the top of 
the existing loop.

But nested loops are easy, its just an extra indentation level:

>>> j = 0
>>> while j < 5:
...n = 0
...while n < 10:
...  print n,
...  n += 1
...j += 1
...

> using nested while statements, or suggest a better use of the ifs? 

Using 'if's I'd do:

# guessing loop
while (guess != the_number):
if tries >= TRY_LIMIT:
   print "Too many tries"
   break

if (guess > the_number):
print "Lower..."
else:
print "Higher..."

guess = int(raw_input("Take a guess: "))
tries += 1

> Also, while asking for help from this forum: for short pieces of code
> such as these, is it appropriate to enter them as inline text

Yes, if it gets above a screenful(50 lines?) then an 
attachment (or a url) is usually better.

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] A fun puzzle

2007-08-24 Thread Dick Moores
At 11:49 AM 8/23/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>>Two reasons. First, looking up a name that is local to a function 
>>>is faster than looking up a global name. To find the value of 
>>>'str', the interpreter has to look at the module namespace, then 
>>>the built-in namespace. These are each dictionary lookups. Local 
>>>values are stored in an array and accessed by offset so it is much faster.
>>Wow, what DON'T you understand?
>
>Lots, actually :-) There is a whole 'nother tier or two of Python 
>expert above me that I can't touch. I just parrot back what I hear 
>them saying. :-)
>
>>Please explain "accessed by offset".
>
>IIUC an array is allocated on the call stack to hold references to 
>the local variables. (Anticipating you next question: 
>http://en.wikipedia.org/wiki/Stack_frame) To get the value of the 
>local variable the runtime just has to look up the correct entry in 
>the array. The bytecode has the offset into the array. This is very 
>quick - an indexed lookup.
>
>Normal attribute access such as a module or builtin has to read the 
>value out of a dict which is much more expensive, even with Python's 
>optimized dicts.

Thank you. Nice parroting. :-)


>>This time I added "xrange(10, end, 10)" and did the timing using 
>>the template in the timeit module:
>>template = """
>>def inner(_it, _timer):
>>  _t0 = _timer()
>>  from itertools import chain
>>  end = 100
>>  for _i in _it:
>>  for x in chain(xrange(1, end, 10), xrange(2, end, 10),
>>  xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10),
>>  xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10),
>>  xrange(9, end, 10), xrange(10, end, 10)):
>>  pass
>>  _t1 = _timer()
>>  return _t1 - _t0
>>"""
>>This gets always close to 71 msec per loop.
>>
>>template = """
>>def inner(_it, _timer):
>>  _t0 = _timer()
>>  end = 100
>>  for _i in _it:
>>  for x in xrange(end):
>>  pass
>>  _t1 = _timer()
>>  return _t1 - _t0
>>"""
>>This gets always close to 84 msec per loop.
>>So they're not the same! And yours is the faster one! Because 
>>itertools.chain() is written in C, I suppose.
>
>That is very strange. I did a simple timer with time.time() and 
>found that my original (1-9) version was consistently a little 
>slower than the simple xrange(). And xrange is written in C too, and 
>the chain version adds a layer over xrange. You should check your 
>code carefully, that is a very surprising result.

Yes, surprising. But the templates pasted above are exactly what I 
used in 2 copies of timeit.py. I don't know what to check. Can you 
see what's wrong?  I just ran both of those again, with very similar results.

Following your lead I've now done some timing using time.time():

==
from __future__ import division
from itertools import chain
import time

end = 100
timeTotal = 0
for c in range(100):
 timeStart = time.time()
 for x in chain(xrange(1, end, 10), xrange(2, end, 10),
 xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10),
 xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10),
 xrange(9, end, 10), xrange(10, end, 10)):
 pass

 timeEnd = time.time()
 timeElapsed = timeEnd - timeStart
 timeTotal += timeElapsed
avgTime = timeTotal/c
print "with chain avgTime was %.4g seconds" % avgTime

"""
results of 5 runs:
with chain avgTime was 0.2072 seconds
with chain avgTime was 0.1916 seconds
with chain avgTime was 0.1913 seconds
with chain avgTime was 0.1921 seconds
with chain avgTime was 0.1915 seconds
(avg is 0.1947 seconds)
"""
=

=
from __future__ import division
import time
end = 100
timeTotal = 0
for c in range(100):
 timeStart = time.time()
 for x in xrange(end):
 pass
 timeEnd = time.time()
 timeElapsed = timeEnd - timeStart
 timeTotal += timeElapsed
avgTime = timeTotal/c
print "no chain avgTime was %.4g seconds" % avgTime

"""
results of 5 runs:
no chain avgTime was 0.2104 seconds
no chain avgTime was 0.2109 seconds
no chain avgTime was 0.1946 seconds
no chain avgTime was 0.1948 seconds
no chain avgTime was 0.1946 seconds
(avg is 0.2011 seconds)
"""
=
When I ran the above 2 scripts, I alternated between them. Don't 
really see that one is decisively faster than the other.

Dick



==
   Bagdad Weather
 

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


Re: [Tutor] Off Topic: xrange, WAS: Re: the and command

2007-08-24 Thread Dave Kuhlman
On Fri, Aug 24, 2007 at 09:52:16AM -0400, Kent Johnson wrote:

Kent and Alan -

Thanks for encouraging me to do a little reading and experimenting.

I thought xrange() returned an iterator.  I was wrong.

Actually xrange() returns an xrange object which, according to the
docs, is "an opaque sequence".

Small points I suppose, but ...

There are some differences between an xrange object and an
iterator:

- an xrange object can be used multiple times to produce the
  sequence.  An iterator is exhausted after it has produced its
  sequence.  At least, thats what the docs seem to say, although, I
  suppose, it depends on the implementation of the individual
  iterator.  See http://docs.python.org/lib/typeiter.html.

- an xrange object is index-able; iterators are not.

Here is the relavant part from the docs:

  xrange([start,] stop[, step])
This function is very similar to range(), but returns an
`xrange object'' instead of a list. This is an opaque sequence
type which yields the same values as the corresponding list,
without actually storing them all simultaneously. The advantage
of xrange() over range() is minimal (since xrange() still has
to create the values when asked for them) except when a very
large range is used on a memory-starved machine or when all of
the range's elements are never used (such as when the loop is
usually terminated with break).
http://docs.python.org/lib/built-in-funcs.html#l2h-80

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] using in over several entities

2007-08-24 Thread Alan Gauld

"Chris Calloway" <[EMAIL PROTECTED]> wrote 

> >>> dbs = set(['oracle','mysql','postgres','infomix','access'])
> >>> mine = set(['oracle','mysql','bdb'])
> >>> dbs & mine
> set(['oracle', 'mysql'])
> >>> dbs - mine
> set(['access', 'infomix', 'postgres'])

Interesting. I didn't know about the & and - set operations.
Thanks for the pointer.

Alan G

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


Re: [Tutor] A fun puzzle

2007-08-24 Thread Kent Johnson
Dick Moores wrote:
>>> This time I added "xrange(10, end, 10)" and did the timing using 
>>> the template in the timeit module:
>>> template = """
>>> def inner(_it, _timer):
>>>  _t0 = _timer()
>>>  from itertools import chain
>>>  end = 100
>>>  for _i in _it:
>>>  for x in chain(xrange(1, end, 10), xrange(2, end, 10),
>>>  xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10),
>>>  xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10),
>>>  xrange(9, end, 10), xrange(10, end, 10)):
>>>  pass
>>>  _t1 = _timer()
>>>  return _t1 - _t0
>>> """
>>> This gets always close to 71 msec per loop.
>>>
>>> template = """
>>> def inner(_it, _timer):
>>>  _t0 = _timer()
>>>  end = 100
>>>  for _i in _it:
>>>  for x in xrange(end):
>>>  pass
>>>  _t1 = _timer()
>>>  return _t1 - _t0
>>> """
>>> This gets always close to 84 msec per loop.
>>> So they're not the same! And yours is the faster one! Because 
>>> itertools.chain() is written in C, I suppose.
>> That is very strange. I did a simple timer with time.time() and 
>> found that my original (1-9) version was consistently a little 
>> slower than the simple xrange(). And xrange is written in C too, and 
>> the chain version adds a layer over xrange. You should check your 
>> code carefully, that is a very surprising result.
> 
> Yes, surprising. But the templates pasted above are exactly what I 
> used in 2 copies of timeit.py. I don't know what to check. Can you 
> see what's wrong?  I just ran both of those again, with very similar results.

So you actually pasted that code into timeit.py? That is a pretty 
unconventional use of the module! I wonder if there is something strange 
going on there?

Using timeit more conventionally I get unsurprising results. This program:

from timeit import Timer

setup = 'from itertools import chain'
stmt = '''end = 100
for x in chain(xrange(1, end, 10), xrange(2, end, 10),
 xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10),
 xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10),
 xrange(9, end, 10), xrange(10, end, 10)):
 pass
'''

print min(Timer(stmt, setup=setup).repeat(number=10))

stmt = '''end = 100
for x in xrange(end):
 pass
'''

print min(Timer(stmt).repeat(number=10))


has output:
0.497083902359
0.359513998032

which is more in line with what I would expect.

I can't account for the variations between different timing methods.

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


Re: [Tutor] using in over several entities

2007-08-24 Thread Alan Gauld

"Tino Dai" <[EMAIL PROTECTED]> wrote 

> dbs= ['oracle','mysql','postgres','infomix','access']
> 
> and we wanted to do this:
> 
> if 'oracle' in dbs or 'mysql' in dbs or 'bdb' in dbs:
>   <... do something ...>
> 
> Is there a short way or writing this? Something like
>('oracle','mysql','bdb') in dbs

You could use sets and check the intersection:

dbs = set(['oracle','mysql','postgres','infomix','access'])
test = set(['oracle','mysql','dbd'])

if dbs.intersection(test):

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] Off Topic: xrange, WAS: Re: the and command

2007-08-24 Thread Kent Johnson
Dave Kuhlman wrote:
> I thought xrange() returned an iterator.  I was wrong.
> 
> Actually xrange() returns an xrange object which, according to the
> docs, is "an opaque sequence".

Interesting. So an xrange object is an iterable sequence, not an iterator.

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


Re: [Tutor] Off Topic: xrange, WAS: Re: the and command

2007-08-24 Thread Eric Brunson
Kent Johnson wrote:
> Dave Kuhlman wrote:
>   
>> I thought xrange() returned an iterator.  I was wrong.
>>
>> Actually xrange() returns an xrange object which, according to the
>> docs, is "an opaque sequence".
>> 
>
> Interesting. So an xrange object is an iterable sequence, not an iterator.
>
>   

It's a fine distinction to the language lawyers.  Most of the time I see 
the term "iterator" used, the speaker is referring to an "iterable 
container", which is a container that defines an "__iter__()" method.  
That method returns the actual "iterator object", i.e. an object that 
implements an "__iter__()" and a "next()" method which returns the next 
item from the container until exhausted, then raises StopIteration.

So, xrange doesn't implement the next() method, but the object returned 
by xrange.__iter__() does, and *that* is the iterator object, though 
xrange can be referred to as "iterable".

Just semantics, but important when trying to be ultra-clear.  :-)

e.

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


Re: [Tutor] using in over several entities

2007-08-24 Thread Chris Calloway
Alan Gauld wrote:
> "Chris Calloway" <[EMAIL PROTECTED]> wrote 
> 
> dbs = set(['oracle','mysql','postgres','infomix','access'])
> mine = set(['oracle','mysql','bdb'])
> dbs & mine
>> set(['oracle', 'mysql'])
> dbs - mine
>> set(['access', 'infomix', 'postgres'])
> 
> Interesting. I didn't know about the & and - set operations.
> Thanks for the pointer.

They just invoke special methods, of course:

s.issubset(t) s <= t   __le__
s.issuperset(t)   s >= t   __ge__
s.union(t)s | t__or__
s.intersection(t) s & t__and__
s.difference(t)   s - t__sub__
s.symmetric_difference(t) s ^ t__xor__
s.update(t)   s |= t   __ior__
s.intersection_update(t)  s &= t   __iand__
s.difference_update(t)s -= t   __isub__
s.symmetric_difference_update(t)  s ^= t   __ixor__

Good times!

The advantage of the s.method(t) versions are, in Python 2.3.1 and
after, they will accept any, cough, iterable as argument t, whereas the
operator versions require set objects on both side of the operator:

 >>> set(xrange(10)).issubset(xrange(20))
True
 >>>

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599



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


Re: [Tutor] Help Request: Nested While commands

2007-08-24 Thread Chris Calloway
Paul W Peterson wrote:
> Could you provide a way to achieve this 
> using nested while statements, or suggest a better use of the ifs?

You could use one while statement.

while guess != the_number and tries < 5:

I can't think of a *good* way to use nested whiles for your problem.

> Ellicott, Colorado
> The Technological Capital of Mid Central Eastern El Paso County, Colorado.

Nice.

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599

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


Re: [Tutor] A fun puzzle

2007-08-24 Thread Dick Moores
At 10:22 AM 8/24/2007, Kent Johnson wrote:
>Dick Moores wrote:
This time I added "xrange(10, end, 10)" and did the timing using 
the template in the timeit module:
template = """
def inner(_it, _timer):
  _t0 = _timer()
  from itertools import chain
  end = 100
  for _i in _it:
  for x in chain(xrange(1, end, 10), xrange(2, end, 10),
  xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10),
  xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10),
  xrange(9, end, 10), xrange(10, end, 10)):
  pass
  _t1 = _timer()
  return _t1 - _t0
"""
This gets always close to 71 msec per loop.

template = """
def inner(_it, _timer):
  _t0 = _timer()
  end = 100
  for _i in _it:
  for x in xrange(end):
  pass
  _t1 = _timer()
  return _t1 - _t0
"""
This gets always close to 84 msec per loop.
So they're not the same! And yours is the faster one! Because 
itertools.chain() is written in C, I suppose.
>>>That is very strange. I did a simple timer with time.time() and 
>>>found that my original (1-9) version was consistently a little 
>>>slower than the simple xrange(). And xrange is written in C too, 
>>>and the chain version adds a layer over xrange. You should check 
>>>your code carefully, that is a very surprising result.
>>Yes, surprising. But the templates pasted above are exactly what I 
>>used in 2 copies of timeit.py. I don't know what to check. Can you 
>>see what's wrong?  I just ran both of those again, with very similar results.
>
>So you actually pasted that code into timeit.py?

Yeah. :-( I think I learned on the Tutor list to do it that way, but 
I'm not sure. Thanks for showing me a correct way.

>That is a pretty unconventional use of the module! I wonder if there 
>is something strange going on there?
>
>Using timeit more conventionally I get unsurprising results. This program:
>
>from timeit import Timer
>
>setup = 'from itertools import chain'
>stmt = '''end = 100
>for x in chain(xrange(1, end, 10), xrange(2, end, 10),
> xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10),
> xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10),
> xrange(9, end, 10), xrange(10, end, 10)):
> pass
>'''
>
>print min(Timer(stmt, setup=setup).repeat(number=10))
>
>stmt = '''end = 100
>for x in xrange(end):
> pass
>'''
>
>print min(Timer(stmt).repeat(number=10))
>
>
>has output:
>0.497083902359
>0.359513998032
>
>which is more in line with what I would expect.

Using your exact code, I just got
0.737564690484
1.17399585702

Which is the reverse of your result, but on a slower computer. What's 
up with that??

>I can't account for the variations between different timing methods.

Dick



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


Re: [Tutor] A fun puzzle

2007-08-24 Thread Kent Johnson
Dick Moores wrote:
> At 10:22 AM 8/24/2007, Kent Johnson wrote:
>> So you actually pasted that code into timeit.py?
> 
> Yeah. :-( I think I learned on the Tutor list to do it that way, but I'm 
> not sure. Thanks for showing me a correct way.

I hope not!

>> Using timeit more conventionally I get unsurprising results. This 
>> program has output:
>> 0.497083902359
>> 0.359513998032
>>
>> which is more in line with what I would expect.
> 
> Using your exact code, I just got
> 0.737564690484
> 1.17399585702
> 
> Which is the reverse of your result, but on a slower computer. What's up 
> with that??

I have no idea. Some strange interaction with the memory cache? I'm 
running Python 2.5.1 on a MacBook Pro (Intel Core 2 Duo processor). How 
about you?

Time for one of the über-wizards to chime in, maybe :-) or post the code 
and results on comp.lang.python and see what they say there.

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


Re: [Tutor] A fun puzzle

2007-08-24 Thread Dick Moores


At 12:12 PM 8/24/2007, Kent Johnson wrote:
Dick Moores wrote:
At 10:22 AM 8/24/2007, Kent
Johnson wrote:
So you actually pasted that code
into timeit.py?Yeah. :-( I think I learned on the Tutor list
to do it that way, but I'm not sure. Thanks for showing me a correct
way.
I hope not!

Using timeit more conventionally
I get unsurprising results. This program has output:
0.497083902359
0.359513998032
which is more in line with what I would expect.Using your
exact code, I just got
0.737564690484
1.17399585702
Which is the reverse of your result, but on a slower computer. What's up
with that??
I have no idea. Some strange interaction with the memory cache? I'm
running Python 2.5.1 on a MacBook Pro (Intel Core 2 Duo processor). How
about you?
Python 2.5; Dell Dimension 4600i; 2.80 gigahertz Intel
Pentium 4. The other day my computer guy put in a 512K stick of
memory, making the total 1024K. However, by doing so he shut off the dual
channel memory. I understand now that he should have put in a pair of
256k sticks to go with the pair that were already there. Seems
far-fetched, but could this be the cause of the problem with the timings?
Nah, you're talking about one of these caches that Belarc says I have:

8 kilobyte primary memory cache
512 kilobyte secondary memory cache 
Right?

Time for one of the über-wizards
to chime in, maybe :-) or post the code and results on comp.lang.python
and see what they say there.
Dick


===
 
Bagdad Weather
<
http://weather.yahoo.com/forecast/IZXX0008_f.html>


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


Re: [Tutor] A fun puzzle

2007-08-24 Thread Dick Moores
Dick Moores wrote:
>At 10:22 AM 8/24/2007, Kent Johnson wrote:
>>So you actually pasted that code into timeit.py?
>Yeah. :-( I think I learned on the Tutor list to do it that way, but 
>I'm not sure. Thanks for showing me a correct way.

I hope not!

>>Using timeit more conventionally I get unsurprising results. This 
>>program has output:
>>0.497083902359
>>0.359513998032
>>
>>which is more in line with what I would expect.
>Using your exact code, I just got
>0.737564690484
>1.17399585702
>Which is the reverse of your result, but on a slower computer. 
>What's up with that??


Kent,

That result was gotten using Ulipad. Thought I'd try it at my command 
line (several times, of course--I've reported what seemed to be 
representative data).

Using command line:
0.673447044247
0.511676204657

Using IDLE:
0.845213567646
0.685519807685

Using Wing Pro (executing with Alt+F5)
0.940486290855
0.998467123615

Is it possible that the timeit module should be used only at the command line?

Dick

==
   Bagdad Weather
 

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


Re: [Tutor] A fun puzzle

2007-08-24 Thread Ken Oliver


-Original Message-
>From: Dick Moores <[EMAIL PROTECTED]>
>Sent: Aug 24, 2007 4:30 PM
>To: Python Tutor List 
>Subject: Re: [Tutor] A fun puzzle
>
>Dick Moores wrote:
>>At 10:22 AM 8/24/2007, Kent Johnson wrote:
>>>So you actually pasted that code into timeit.py?
>>Yeah. :-( I think I learned on the Tutor list to do it that way, but 
>>I'm not sure. Thanks for showing me a correct way.
>
>I hope not!
>
>>>Using timeit more conventionally I get unsurprising results. This 
>>>program has output:
>>>0.497083902359
>>>0.359513998032
>>>
>>>which is more in line with what I would expect.
>>Using your exact code, I just got
>>0.737564690484
>>1.17399585702
>>Which is the reverse of your result, but on a slower computer. 
>>What's up with that??
>
>
>Kent,
>
>That result was gotten using Ulipad. Thought I'd try it at my command 
>line (several times, of course--I've reported what seemed to be 
>representative data).
>
>Using command line:
>0.673447044247
>0.511676204657
>
>Using IDLE:
>0.845213567646
>0.685519807685
>
>Using Wing Pro (executing with Alt+F5)
>0.940486290855
>0.998467123615
>
>Is it possible that the timeit module should be used only at the command line?
>
>Dick

The IDLE numbers match those on my machine to within 0.001.  For what it is 
worth.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A fun puzzle

2007-08-24 Thread Kent Johnson
Dick Moores wrote:
>> Using your exact code, I just got
>> 0.737564690484
>> 1.17399585702
>> Which is the reverse of your result, but on a slower computer. 
> 
> That result was gotten using Ulipad. Thought I'd try it at my command 
> line (several times, of course--I've reported what seemed to be 
> representative data).
> 
> Using command line:
> 0.673447044247
> 0.511676204657
> 
> Using IDLE:
> 0.845213567646
> 0.685519807685
> 
> Using Wing Pro (executing with Alt+F5)
> 0.940486290855
> 0.998467123615

Curiouser and curiouser...

> Is it possible that the timeit module should be used only at the command line?

No, you should be able to use it anywhere Python works. I get very 
similar results running it Terminal and from TextMate...

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


[Tutor] Spawning terminals from Python - A failed question

2007-08-24 Thread wormwood_3
Hello all,

I had this question all written up, then found I had the answer:-) So I decided 
to share anyway in case anyone found it useful
--
I am trying to write a script that will open terminal windows for me, based on 
certain criteria. In this case, gnome-terminals, in Ubuntu, but my question is 
more general: How do I launch a command from a script and having it continue 
running? The pertinent part of my script right now:

# Spawn the 4 terminals, with needed positions and sizes, then exit quietly:
"gnome-terminal --geometry=%dx%d+%d+%d" % (t1width, t1height, t1posx, t1posy)
"gnome-terminal --geometry=%dx%d+%d+%d" % (t2width, t2height, t2posx, t2posy)
"gnome-terminal --geometry=%dx%d+%d+%d" % (t3width, t3height, t3posx, t3posy)
"gnome-terminal --geometry=%dx%d+%d+%d" % (t4width, t4height, t4posx, t4posy)


I need something to pass these lines to of course, to actually launch them. I 
thought first of the commands module 
(http://docs.python.org/lib/module-commands.html), but I don't:q
 want to get status or output, I want to basically spawn the process so it 
keeps running regardless of what the script does next (like running something 
with " &" after it in linux).
---
All I ended up having to do was:
>>> import commands
>>> commands.getoutput("gnome-terminal")
...
>>>

And the terminal launched. When I closed the interpreter, the terminal stayed 
open fine. So getoutput() was the ticket.

-Sam


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


Re: [Tutor] Spawning terminals from Python - A failed question

2007-08-24 Thread Alan Gauld

"wormwood_3" <[EMAIL PROTECTED]> wrote

>  want to basically spawn the process so it keeps running regardless
> of what the script does next (like running something with " &" after 
> it in linux).

Umm, so just put the ampersand at the end of the command string and
call os.system()

> All I ended up having to do was:
 import commands
 commands.getoutput("gnome-terminal")

However both os.system and the commands module are deprecated in 
favour
of the new(ish) subprocess module where the equivalent incantation 
would be:

p = subprocess.Popen("gnome-terminal", shell=True)HTH,-- Alan 
GauldAuthor of the Learn to Program web 
sitehttp://www.freenetpages.co.uk/hp/alan.gauld 


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


[Tutor] Read dictionary data in a specific order...

2007-08-24 Thread Trey Keown
Hello.
I would like to know, how can I read (or sort) a dictionary in a certain
order?
say this is my dictionary-
attrs={u'title': u'example window title', u'name': u'SELF', u'icon':
u'e.ico'}
how could I get the data so that u'name' is read first, u'title' second,
and u'icon' third?
thanks so much for any help-
Trey

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


Re: [Tutor] the and command

2007-08-24 Thread Ricardo Aráoz
Alan Gauld wrote:
> "max baseman" <[EMAIL PROTECTED]> wrote
>> im checking if a number is in all 5 of the other lists and when
>> i use the and command it seems to just be checking if it's in a 
>> least
>> one of the others,
> 
> 
>> for num in l2 and l3 and l4 and l5 and l6: # here seems to be the
> 
> Try:
> 
> if num in I2 and num in I3 and num in I4 and num in I5 and num in I6:
> 

or also : if num in l1 + l2 + l3 + l4 + l5 :

> In your case you are 'and'ing the lists which is a boolean expression
> and because of how Python does short circuit evaluation it returns
> the last list
> 
 a = [1,2]
 b = [3,4]
 a and b
> [3, 4]
> 
> so
> 
> for n in a and b:
> 
> is the same as
> 
> for n in b:
> 
> which iterates over b...
> 
> HTH,
> 


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


Re: [Tutor] HOWTO: adding to sys.path the simplest way.

2007-08-24 Thread Ricardo Aráoz
Tim Johnson wrote:
> I have a seperate library directory both on my work station on
> the the remote servers that I write applications for..
> 
> I commonly use sys.path.append('/path/to/mylibraries') in my 
> python code.
> 
> That code has to be placed in any standalone script that I write.
> I can also place that path in a system file. On my kubuntu
> workstation, it is /var/lib/python-support/python2.5/.path
> 
> I believe that path is different on the solaris or redhat servers
> that I provide scripts to. Furthermore, any update of the python version
> will necessitate editing of the new .path file.
> 
> I would welcome some opinions on this matter.
> Thanks
> Tim
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

You might put your libraries in your development directory :

/path/devel
/path/devel/mylibraries
/path/devel/mylibraries/graphiclibraries
/path/devel/mylibraries/databaselibraries
/path/devel/myapplications/mynewapplication

Then inside /path/devel/myapplications/mynewapplication/myprogram.py
when you want to access a module you just write :

import mylibraries.mygeneralmodule
from mylibraries.mygeneralmodule import x

import mylibraries.graphiclibraries.mygraphiclibrary
from mylibraries.graphiclibraries.mygraphiclibrary import x

import mylibraries.databaselibraries.mygraphiclibrary
from mylibraries.databaselibraries.mygraphiclibrary import x

Of course /path/devel must be in your path, but as long as the rest of
the structure remains unchanged you may place your stuff anywhere.

HTH

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


Re: [Tutor] the and command

2007-08-24 Thread Kent Johnson
Ricardo Aráoz wrote:
> Alan Gauld wrote:
>> "max baseman" <[EMAIL PROTECTED]> wrote
>>> im checking if a number is in all 5 of the other lists and when
>>> i use the and command it seems to just be checking if it's in a 
>>> least
>>> one of the others,
>>
>>> for num in l2 and l3 and l4 and l5 and l6: # here seems to be the
>> Try:
>>
>> if num in I2 and num in I3 and num in I4 and num in I5 and num in I6:
>>
> 
> or also : if num in l1 + l2 + l3 + l4 + l5 :

No, that has a different meaning, it is true if num is in *any* of the 
lists; the original version requires num to be in *all* of the lists.

Also your version will compute the sum of lists every time through the 
loop which you don't really want...

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


Re: [Tutor] Read dictionary data in a specific order...

2007-08-24 Thread Alan Gauld
"Trey Keown" <[EMAIL PROTECTED]> wrote

> I would like to know, how can I read (or sort) a dictionary in a 
> certain
> order?

Dictionaries are by design unsorted and indeed may even change
their order during their lifetime.

> attrs={u'title': u'example window title', u'name': u'SELF', u'icon':
> u'e.ico'}
> how could I get the data so that u'name' is read first, u'title' 
> second,
> and u'icon' third?

Normally you would sort the keys of the dictionary but since
your order is not a natural sort order then the easiest way is
probably to create a list of the keys you want in the order you
want them. Thus:

keys = ['name','title','icon']
for key in keys: print attrs[key]

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] Spawning terminals from Python - A failed question

2007-08-24 Thread wormwood_3
>>Umm, so just put the ampersand at the end of the command string and
>>call os.system()

Not sure what the point of this variation would be if os is being deprecated 
along with commands...

>>However both os.system and the commands module are deprecated in 
>>favour
>>of the new(ish) subprocess module where the equivalent incantation 
>>would be:
>>p = subprocess.Popen("gnome-terminal", shell=True)HTH,-- Alan 

Good to know! I will start using this instead.

-Sam




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


Re: [Tutor] Read dictionary data in a specific order...

2007-08-24 Thread Trey Keown
> "Trey Keown" <[EMAIL PROTECTED]> wrote
>
>> I would like to know, how can I read (or sort) a dictionary in a
>> certain
>> order?
>
> Dictionaries are by design unsorted and indeed may even change
> their order during their lifetime.
>
>> attrs={u'title': u'example window title', u'name': u'SELF', u'icon':
>> u'e.ico'}
>> how could I get the data so that u'name' is read first, u'title'
>> second,
>> and u'icon' third?
>
> Normally you would sort the keys of the dictionary but since
> your order is not a natural sort order then the easiest way is
> probably to create a list of the keys you want in the order you
> want them. Thus:
>
> keys = ['name','title','icon']
> for key in keys: print attrs[key]
>
--
Okay, the reason I need to know this is that expat, my xml parsing module,
returns the attributes of an xml element as a dictionary. Now that i've
done what you recommended above, my xml parsing program returns the
dictionary's value as the value and the tag.
here's my code-
"
...
global window_attrs_key_order
window_attrs_key_order = ["name", "title", "icon"]
def start_element(name, attrs):
global window_attrs_key_order
if name in acceptedelements:
..
if name == "window":
print attrs.iteritems()
for (tag,val) in attrs.iteritems():
if tag in window_attrs_key_order:
for tag in window_attrs_key_order:
if tag == u"name":
print "%s%s = Tk()" 
%(whitespace, val)
print "***^^^%s^^^***" 
%val
whatwindow = val
if tag == u"title":
print 
"%s%s.title(\"%s\")" % (whitespace, whatwindow, val)
if tag == u"icon":
if val == "NONE":
print "#>NO 
ICON"
else:
print 
"%s%s.iconbitmap(\"%s\")" %(whitespace, whatwindow, val)
else:
print "#-Error, unrecognized 
attribute in window element...-"
..
"

here's a likely example of what expat would spit out the attributes as-

"
attrs={u'title': u'example window title', u'name': u'SELF', u'icon':
u'e.ico'}
"

and the program output is this-

"
..

Example Window Title = Tk()
***^^^Example Window Title^^^***
Example Window Title.title("Example Window Title")
Example Window Title.iconbitmap("Example Window Title")
SELF = Tk()
***^^^SELF^^^***
SELF.title("SELF")
SELF.iconbitmap("SELF")
e.ico = Tk()
***^^^e.ico^^^***
e.ico.title("e.ico")
e.ico.iconbitmap("e.ico")
"

why would you think that the program would do this?
Trey



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


[Tutor] Question about classes

2007-08-24 Thread Ara Kooser
Hello all,

   I am working on trying to understand classes by creating a
character generator for a rpg. I know I am doing something silly but I
am not sure what. When I run the program I and type no when prompted I
get the following message:
Traceback (most recent call last):
  File "/Users/ara/Documents/ct_generator.py", line 10, in 
class Main:
  File "/Users/ara/Documents/ct_generator.py", line 68, in Main
reroll()
  File "/Users/ara/Documents/ct_generator.py", line 53, in reroll
upp()
NameError: global name 'upp' is not defined

I guess it doesn't recognize that I want to call the function upp()
again. I think I might be using the wrong syntax here. My code is
below. Thank you any help or guidance.

Ara

###
#Version: not even 0.1
#By: Ara Kooser
#


import random


class Main:



print """Welcome to the Classic Traveller character generator.
Written in Python"""
print """Press return to generate a character"""

raw_input()



def upp():
print """Generating your UPP."""
print

strength = 0
dexterity = 0
endurance = 0
intelligence = 0
education = 0
social = 0

strength = random.randrange(2,12)
dexterity = random.randrange(2,12)
endurance = random.randrange(2,12)
intelligence = random.randrange(2,12)
education = random.randrange(2,12)
social = random.randrange(2,12)

return strength, dexterity, endurance, intelligence, education, social


print upp()

def reroll():

a = raw_input("Are you satisfied with your UPP? Choose yes or
no.").lower()
try:

if a == "yes":
career()

elif a == "no":
upp()

else:
print "Please choose a valid option."
print
reroll()

except ValueError:
print "Please choose a valid option."
print
reroll()

return

print """You have a chance to reroll if needed."""
reroll()

def career():
print """You will now choose are career path for your character."""













-- 
Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis
an sub cardine glacialis ursae.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about classes

2007-08-24 Thread Noufal Ibrahim
Ara Kooser wrote:
> Hello all,
> 
>I am working on trying to understand classes by creating a
> character generator for a rpg. I know I am doing something silly but I
> am not sure what. When I run the program I and type no when prompted I
> get the following message:
> Traceback (most recent call last):
>   File "/Users/ara/Documents/ct_generator.py", line 10, in 
> class Main:
>   File "/Users/ara/Documents/ct_generator.py", line 68, in Main
> reroll()
>   File "/Users/ara/Documents/ct_generator.py", line 53, in reroll
> upp()
> NameError: global name 'upp' is not defined
> 
> I guess it doesn't recognize that I want to call the function upp()
> again. I think I might be using the wrong syntax here. My code is
> below. Thank you any help or guidance.

In Python, if you want to call an object method, you have to do so 
explicitly via the object. Otherwise, it looks for a local/global 
variable of the same name.

For example,

def foo():
   print "I am foo!"

class Foo(object):
   def __init__(self):
   pass

   def foo(self):
   print "I am Foo.foo"

   def display(self):
   self.foo()
   foo()

 >>> x=Foo()
 >>> x.display()
I am Foo.foo
I am foo!


All objects methods are passed the object instance explicitly as their 
first argument. It's conventionally called "self" (similar to the "this" 
pointer in C++ if you're familiar with it).

Let me know if there's something that's not clear.

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