Re: [Tutor] Sum of Scores

2007-07-26 Thread Luke Paireepinart
Tiger12506 wrote:
>> bhaaluu wrote:
>> 
>>> Greetings,
>>>
>>> Beautiful! Thank you SO much for all the variations.
>>> I'm so sure I'll have much to learn from them. This
>>> is exactly the kind of stuff I'm currently studying.
>>>   
>
> I assume this is for me. Thank you kindly! :-)
>
>   
>>> I have a question for the list.
>>> After I posted my snippet, I added time to import,
>>> and a time.sleep(1) line to the code. The reason
>>> I did this is because I'm under the (possibly mistaken?)
>>> impression that random uses the computer
>>> time as a random number generator 'seed',
>>> for generating pseudo-random numbers?
>>>
>>>   
>> It uses time, it may also use other things.
>> However, this is only to initialize the random number generator.
>> You only need one seed and from that you can generate an infinitely long
>> string of pseudo-random numbers.
>> 
>
> Not infinitely long. From the docs -
>
> [Quote]
> Almost all module functions depend on the basic function random(), which 
> generates a random float uniformly in the semi-open range [0.0, 1.0). Python 
> uses the Mersenne Twister as the core generator. It produces 53-bit 
> precision floats and has a period of 2**19937-1. The underlying 
> implementation in C is both fast and threadsafe. The Mersenne Twister is one 
> of the most extensively tested random number generators in existence. 
> However, being completely deterministic, it is not suitable for all 
> purposes, and is completely unsuitable for cryptographic purposes.
> [/Quote]
>
> So only if you use the random functions
> 4.3154247973881626480552355163379e+6001
> times would the pattern repeat itself. Until then, you're safe. ;-)
>   
Well, I was trying to emphasize that it was, for pretty much all intents 
and purposes, infinite.
via timeit, my computer can perform approximately 400 
random.random()s per second.
 >>> x = timeit.Timer('random.random()','import random')
 >>> x.timeit(400)
1.0523957653835794

4*10**6001 / 4*10**6 is still 10**5095 seconds before the period is 
repeated (and remember this is when i'm trying to cause a repetition, 
not using the module normally!)
The relationship between seconds and years is
 >>> 60*60*24*365.25
31579200.0
i.e. 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, 
and 365.25 days per year.

Therefore, it would take my computer
 >>> (10**5095) / int(60*60*24*365.25)
years (which is too long to post in this e-mail)
in fact, it's so large I am having a hard time believing I didn't make a 
mistake in my calculations somewhere.
somewhere on the order of a centillion**quadrillion years.
(a centillion is 10**303 or
1000




 and a quadrillion is 10**15 or 1000.
In other words, approx. (very approximately :)) 10**4545 years)
Because the possibility of my computer even existing after that long is 
effectively zero, I consider the pattern to never repeat :)
>> In other words, the only way you'd end up getting the same value is if
>> you ran the program, quit it, then ran it again, in less than a second.
>> (or possibly reloaded the module)
>> 
>
> This freaked me out for a bit with a c program I wrote a while back. It was 
> a screen saver built upon random values. I would double click its icon, and 
> accidently jerk the mouse, double click it again. I thought I noticed that 
> the two screens were the same. A little research brought me to that tidbit 
> of information.
>
> I'm not sure if reloading the module would or not. I would think that the 
> seeding of the generator would occur at import of the random module. In 
> which case, it would only happen once because import modules are not 
> imported twice in the same session. (see recent threads)
>   
by reloading I didn't mean importing it again.
I meant reload()ing it.
Well, we can test this pretty easily.

 >>> import random
 >>> for x in range(10):
reload(random)
print random.random()

   

0.322316243317

0.223659531704

0.991195051657

0.0349410934903

0.586833655938

0.0090626236054

0.0650813786008

0.198508992645

0.0567290580105

0.0446836944247


Nope, I guess reloading it doesn't cause it to reuse the same seed.
See, I thought reload was just a forced 'import'.
But maybe it has some complexity behind it, as per it not reloading() if 
the module hasn't changed?
The docstring isn't a whole lot of help on this:
 >>> help(reload)
Help on built-in function reload in module __builtin__:

reload(...)
reload(module) -> module
   
Reload the module.  The module must have been successfully imported 
before.


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

Re: [Tutor] Sum of Scores

2007-07-26 Thread Terry Carroll
On Thu, 26 Jul 2007, Tiger12506 wrote:

> > But you can call the random functions in your code as often as you want
> > safely.
> >> Perhaps this is a question for the 'language lawyers'?
> >>
> > Not sure what this means.
> 
> I believe it means 'those who know the language inside and out' like a 
> lawyer must know the law.

A little more subtle.  The Jargon File explains it best:

   language lawyer: n.  A person, usually an experienced or senior
   software engineer, who is intimately familiar with many or most of the
   numerous restrictions and features (both useful and esoteric)  
   applicable to one or more computer programming languages. A language
   lawyer is distinguished by the ability to show you the five sentences
   scattered through a 200-plus-page manual that together imply the answer
   to your question "if only you had thought to look there."

http://www.catb.org/jargon/html/L/language-lawyer.html

So it's more about the ability to know and correctly interpret the docs,
especially in the area of how the different provisions interact.  If
you've ever seen an attorney work through the question "does our contract
let us do FOO?" -- well, I'd feel sorry for you if so, because that's time
you're never getting back, but you'd see the similarity.

Now excuse me, I have a contract to go look through.

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


Re: [Tutor] Sum of Scores

2007-07-26 Thread Tiger12506

> bhaaluu wrote:
>> Greetings,
>>
>> Beautiful! Thank you SO much for all the variations.
>> I'm so sure I'll have much to learn from them. This
>> is exactly the kind of stuff I'm currently studying.

I assume this is for me. Thank you kindly! :-)

>> I have a question for the list.
>> After I posted my snippet, I added time to import,
>> and a time.sleep(1) line to the code. The reason
>> I did this is because I'm under the (possibly mistaken?)
>> impression that random uses the computer
>> time as a random number generator 'seed',
>> for generating pseudo-random numbers?
>>
> It uses time, it may also use other things.
> However, this is only to initialize the random number generator.
> You only need one seed and from that you can generate an infinitely long
> string of pseudo-random numbers.

Not infinitely long. From the docs -

[Quote]
Almost all module functions depend on the basic function random(), which 
generates a random float uniformly in the semi-open range [0.0, 1.0). Python 
uses the Mersenne Twister as the core generator. It produces 53-bit 
precision floats and has a period of 2**19937-1. The underlying 
implementation in C is both fast and threadsafe. The Mersenne Twister is one 
of the most extensively tested random number generators in existence. 
However, being completely deterministic, it is not suitable for all 
purposes, and is completely unsuitable for cryptographic purposes.
[/Quote]

So only if you use the random functions
4.3154247973881626480552355163379e+6001
times would the pattern repeat itself. Until then, you're safe. ;-)

> In other words, the only way you'd end up getting the same value is if
> you ran the program, quit it, then ran it again, in less than a second.
> (or possibly reloaded the module)

This freaked me out for a bit with a c program I wrote a while back. It was 
a screen saver built upon random values. I would double click its icon, and 
accidently jerk the mouse, double click it again. I thought I noticed that 
the two screens were the same. A little research brought me to that tidbit 
of information.

I'm not sure if reloading the module would or not. I would think that the 
seeding of the generator would occur at import of the random module. In 
which case, it would only happen once because import modules are not 
imported twice in the same session. (see recent threads)

> But you can call the random functions in your code as often as you want
> safely.
>> Perhaps this is a question for the 'language lawyers'?
>>
> Not sure what this means.

I believe it means 'those who know the language inside and out' like a 
lawyer must know the law.

JS 

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


Re: [Tutor] What exactly is [::-1]?

2007-07-26 Thread Tiger12506
> What are typeseq objects. Searching the python site on "typeseq" draws a 
> blank.
>
> Dick Moores

I believe that means "sequence" type.
list
tuple
string

are the builtins

I debated with myself about dict, decided that it doesn't fit the 
description. That should be all ordered sequence types.

JS 

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


Re: [Tutor] Sum of Scores

2007-07-26 Thread Luke Paireepinart
bhaaluu wrote:
> Greetings,
>
> Beautiful! Thank you SO much for all the variations.
> I'm so sure I'll have much to learn from them. This
> is exactly the kind of stuff I'm currently studying.
>
> I have a question for the list.
> After I posted my snippet, I added time to import,
> and a time.sleep(1) line to the code. The reason
> I did this is because I'm under the (possibly mistaken?)
> impression that random uses the computer
> time as a random number generator 'seed',
> for generating pseudo-random numbers?
>   
It uses time, it may also use other things.
However, this is only to initialize the random number generator.
You only need one seed and from that you can generate an infinitely long 
string of pseudo-random numbers.
In other words, the only way you'd end up getting the same value is if 
you ran the program, quit it, then ran it again, in less than a second.
(or possibly reloaded the module)
But you can call the random functions in your code as often as you want 
safely.
> Perhaps this is a question for the 'language lawyers'?
>   
Not sure what this means.
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What exactly is [::-1]?

2007-07-26 Thread Dick Moores
At 12:37 PM 7/26/2007, Chris Calloway wrote:
>The *other* form of extended slicing, the one with two colons (and no
>commas) is supported by typeseq objects, though.

What are typeseq objects. Searching the python site on "typeseq" draws a blank.

Dick Moores 

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


Re: [Tutor] Sum of Scores

2007-07-26 Thread bhaaluu
Greetings,

Beautiful! Thank you SO much for all the variations.
I'm so sure I'll have much to learn from them. This
is exactly the kind of stuff I'm currently studying.

I have a question for the list.
After I posted my snippet, I added time to import,
and a time.sleep(1) line to the code. The reason
I did this is because I'm under the (possibly mistaken?)
impression that random uses the computer
time as a random number generator 'seed',
for generating pseudo-random numbers?
Perhaps this is a question for the 'language lawyers'?

Cheers!
-- 
bhaaluu at gmail dot com

On 7/26/07, Tiger12506 <[EMAIL PROTECTED]> wrote:
> Note that OP constructed his list so that some values are weighted according
> to the user's decision (Aggressive or defensive), Just let's not forget that
> brilliance~ ;-)
>
> Suggestions below.
>
> > Here is a snippet that might work for one batter:
> >
> > #!/usr/bin/env python
> > # cricket.py
> > # 2007-07-26
> > # b h a a l u u at g m a i l dot c o m
> > import random
> >
> > def batterUp():
> >  score=[1,2,3,4,6,'Out']
> >  totalScore=0
> >  while 1:
> >hit=random.choice(score)
> >if hit != score[-1]:
> >  totalScore=totalScore+hit
> >  print "You batted",hit,"Total runs:",totalScore
> >else:
> >  totalScore=totalScore+0
> >  print "You're OUT! Total runs:",totalScore
> >  break
> >
> > batterUp()
> > # end criket.py
> >
> > Notice that the list, score , has integers and a string in it.
> > I use the integers to add to the running score, and use the
> > string 'Out' to stop the while loop. I just did this, and it ran
> > okay the few times I tried it. YMMV. =)
>
> This is one situation where the python concept of ask forgiveness later is
> convenient.
> For example.
>
> ###
> def play():
>   score = [1,2,3,4,6,'Out']
>   totalScore = 0
>   while 1:
> hit = random.choice(score)
> try:
>   totalScore += int(hit)
>   print "You batted a  %s; Total runs: %d" % (hit,totalScore)
> except ValueError:
>   print "You're OUT! Total runs:", totalScore
>   break
> 
>
> And a way that is even better of which I just thought ;-)
> Use a special value to mean 'out'. This avoids the string problem.
> A value of zero makes the comparisons with if even simpler.
>
> #
> def play():
>   scores = [1,1,2,2,3,4,6,0,0]  #Zero means "out"
>   totalScore = 0
>   while 1:
> hit = random.choice(scores)
> totalScore += hit
> if hit:   # The magic check - even makes sense, if no hit, then
> "out"
>   print "You batted a %d, Total runs: %d" % (hit, totalScore)
> else:
>   print "You're OUT! Total runs: %d" % totalScore
> ##
>
> A sneaky application of a form of encapsulation that OOP people like to use.
> ;-)
> (So you only have to have one play function)
>
> ###
> aggr_scores = [1,2,3,4,4,6,6,0,0,0]
> defe_scores = [1,1,1,2,2,3,4,6,0,0]
>
> user_choice = raw_input("Which?\n\t(a) Aggressive\n\t(b) Defensive\n\nYour
> choice: ")
> if user_choice == 'a':
>   scores = aggr_scores
> elif user_choice == 'b':
>   scores = defe_scores
> else:
>   print "Please choose a or b"
>
> play()
> 
>
> Or even better.
>
> #
> score_lookup = {'a':[1,2,3,4,4,6,6,0,0,0],
>'b':[1,1,1,2,2,3,4,6,0,0]}
>
> # raw_input here
>
> scores = score_lookup[user_choice]
> play()
> #
>
> HTH,
> JS
>
> ___
> 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] Sum of Scores

2007-07-26 Thread R. Alan Monroe

> I want to be able to calculate in the program,.. the total score,..
> either at each successive score,... or when they finally get out.
> Not sure how to do that at this point.

You're on the right track. You need an additional variable to hold the
running total.

Alan

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


Re: [Tutor] adapting a converter openoffice

2007-07-26 Thread Tim Michelsen
> When you say nothing happemed I assume you mean the script
> never terminated? 
Yes, you are right. it does not terminate and only blocks the screen.


As stated on the site the script needs some special parameters of 
Openoffice. Therefore, until I step further, I wrap it around a shell 
script that I will put in my PATH:

#!/bin/bash
###licence
##which licence applies for this script? If not changed it will be 
released under GPL:
#This shell script is free software; you can redistribute it and/or 
modify it under the terms of the GNU General Public License as published 
by the Free Software Foundation; either version 2 of the License, or (at 
your option) any later version.
#
#This shell script  is distributed in the hope that it will be useful, 
but WITHOUT ANY WARRANTY; without even the implied warranty of 
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
General Public License for more details.
#
#You should have received a copy of the GNU General Public License along 
with this shell script ; if not, write to the
#Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 
  02111-1307  USA
#or read the text online: http://www.gnu.org/licenses/gpl.txt
###script description
##convert from/to openoffice document formats using a script from
##http://www.artofsolving.com/opensource/pyodconverter
##see also: http://www.linux.com/articles/61713
#start OpenOffice as a service
soffice -headless -accept="socket,port=8100;urp;"
#get variables
# @1 = SOURCE
# @2 = DESTINATION
#convert command
# /opt/local/pyodconverter $SOURCE $DESTINATION
cd /opt/local/pyodconverter/
python ./DocumentConverter.py $1 $2
exit

Maybe one day I will be able to do this in python using pyodconverter as 
a class...

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


Re: [Tutor] Sum of Scores

2007-07-26 Thread Tiger12506
Note that OP constructed his list so that some values are weighted according 
to the user's decision (Aggressive or defensive), Just let's not forget that 
brilliance~ ;-)

Suggestions below.

> Here is a snippet that might work for one batter:
>
> #!/usr/bin/env python
> # cricket.py
> # 2007-07-26
> # b h a a l u u at g m a i l dot c o m
> import random
>
> def batterUp():
>  score=[1,2,3,4,6,'Out']
>  totalScore=0
>  while 1:
>hit=random.choice(score)
>if hit != score[-1]:
>  totalScore=totalScore+hit
>  print "You batted",hit,"Total runs:",totalScore
>else:
>  totalScore=totalScore+0
>  print "You're OUT! Total runs:",totalScore
>  break
>
> batterUp()
> # end criket.py
>
> Notice that the list, score , has integers and a string in it.
> I use the integers to add to the running score, and use the
> string 'Out' to stop the while loop. I just did this, and it ran
> okay the few times I tried it. YMMV. =)

This is one situation where the python concept of ask forgiveness later is 
convenient.
For example.

###
def play():
  score = [1,2,3,4,6,'Out']
  totalScore = 0
  while 1:
hit = random.choice(score)
try:
  totalScore += int(hit)
  print "You batted a  %s; Total runs: %d" % (hit,totalScore)
except ValueError:
  print "You're OUT! Total runs:", totalScore
  break


And a way that is even better of which I just thought ;-)
Use a special value to mean 'out'. This avoids the string problem.
A value of zero makes the comparisons with if even simpler.

#
def play():
  scores = [1,1,2,2,3,4,6,0,0]  #Zero means "out"
  totalScore = 0
  while 1:
hit = random.choice(scores)
totalScore += hit
if hit:   # The magic check - even makes sense, if no hit, then 
"out"
  print "You batted a %d, Total runs: %d" % (hit, totalScore)
else:
  print "You're OUT! Total runs: %d" % totalScore
##

A sneaky application of a form of encapsulation that OOP people like to use. 
;-)
(So you only have to have one play function)

###
aggr_scores = [1,2,3,4,4,6,6,0,0,0]
defe_scores = [1,1,1,2,2,3,4,6,0,0]

user_choice = raw_input("Which?\n\t(a) Aggressive\n\t(b) Defensive\n\nYour 
choice: ")
if user_choice == 'a':
  scores = aggr_scores
elif user_choice == 'b':
  scores = defe_scores
else:
  print "Please choose a or b"

play()


Or even better.

#
score_lookup = {'a':[1,2,3,4,4,6,6,0,0,0],
   'b':[1,1,1,2,2,3,4,6,0,0]}

# raw_input here

scores = score_lookup[user_choice]
play()
#

HTH,
JS 

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


[Tutor] Code like a Pythonista

2007-07-26 Thread Kent Johnson
For anyone who has wondered, how do I learn to write Python like an 
expert? What do I read after I finish the tutorial? Check out David 
Goodger's "Code Like a Pythonista"
http://python.net/~goodger/projects/pycon/2007/idiomatic/

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


Re: [Tutor] adapting a converter openoffice

2007-07-26 Thread Alan Gauld

"Tim Michelsen" <[EMAIL PROTECTED]> wrote
>
> Therefore I tried to add this code on top of the original converter:
>
> ###get OOo service started first:
> import os
> code = 
> os.system('soffice -headless -accept="socket,port=8100;urp;"')


> when I execute this script nothing happens and I would have to 
> cancel it.

When you say nothing happemed I assume you mean the script
never terminated? If so I suspect your command needs to be run
in the background by placing an ampersand at the end, like so:

code = os.system('soffice -headless -accept="socket,port=8100;urp;" 
&')

That should result in os.system returning with an exit code.

HTH,

Alan G. 


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


Re: [Tutor] Thanks re: [::-1]

2007-07-26 Thread Alan Gauld

"Charles Cuell" <[EMAIL PROTECTED]> wrote

> The one odd thing about Python's slice notation is that the -1 means 
> to
> start from the end and work backwards.  My first inclination would 
> have
> been to assume that -1 means to start at i and go to j by steps 
> of -1
> (only nonempy if j < i).

I mentally resolve this by thinking of sequences as being circular.
Thus the -1 character is the last one - the one before the first.

But that doesn't work for the step size k, you just have to realise
that the minus sign there means work backwards and therefore
start from the second parameter. However...

>>> 'abcdefgh'[3:1:-1]
'dc'
>>> 'abcdefgh'[1:3:-1]
''
>>> 'abcdefgh'[::-1]
'hgfedcba'

It seems that if you do provide values for j,k the first must be 
bigger
than the second to work so Python is being slightly more intelligent
about the default values than I initially thought, but the docs do 
say:

If i or j are omitted or None, they become ``end'' values
(which end depends on the sign of k).
---

How interesting. And thank goodness for the >>> prompt.
- the ultimate arbiter and test...

Alan G.








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


Re: [Tutor] adapting a converter openoffice

2007-07-26 Thread Luke Paireepinart
Tim Michelsen wrote:
> Hello,
> I am Python learning in an early stage.
>
> I am currently trying to code a converter for openoffice based on 
> PyODConverter:
> http://www.artofsolving.com/opensource/pyodconverter
>
> My goal is to be able to run my script from anywhere in the system (put 
> it in Path) and then convert a file from/to openoffice formats to other 
> formats such as doc/pdf etc.
>
> My main problem is how to issue system commands and then run the above 
> script.
>   
> [snip]
> I tried to add this code on top of the original converter:
>
> ###get OOo service started first:
> import os
> code = os.system('soffice -headless -accept="socket,port=8100;urp;"') # 
> Just execute the command, return a success/fail code
>
> when I execute this script nothing happens and I would have to cancel it.
>
> Is there any way to start the OOo service from a python script?
>   
My first hunch would be that the command is running as a background 
service (daemon) so it's not returning control to your program from the 
os.system call because the execution hasn't completed yet.
Try doing a ps -ax or whatever, to see what processes you have running,
after you start your python program and before you quit it.
If you see an instance of soffice running, try terminating it and see if 
your program continues to execute (and probably raises errors).
If this is the case, you will want to use one of the other os commands, 
or subprocess, so that the soffice program will continue to run but 
you'll get control back in your program.
The only caveat to that approach would be that the soffice app 
continuing to run is dependent upon your python program continuing to 
run.  I.E. when you exit the python program, the soffice instance that 
it started (if it started one) will be ended.  Although, you  could 
probably just allow the python program to continue to run.  Not sure, I 
don't know anything about linux and I haven't had to do something 
similar to this before.
hope that he;lps.
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running Python on Gentoo

2007-07-26 Thread Dave Kuhlman
On Thu, Jul 26, 2007 at 01:48:44PM -0600, Eric Brunson wrote:
> 
> Do other interpreters work?
> 
> Try:
> 
> #!/usr/bin/perl
> print "Perl Sucks!!!\n";
> 
> or:

Or, try:

#!/usr/bin/env python

Dave

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


Re: [Tutor] Livewires questions

2007-07-26 Thread Luke Paireepinart
Tonu Mikk wrote:
> Luke, thank you for your quick and complete response.  Based on your 
> suggestions I have already made some progress!  BTW, I am so glad that 
> I can ask this list my Python questions and get help.  I began feeling 
> quite stuck and not knowing where to turn for help.  So, thank you for 
> the great service!
Sure!  I'm happy to he;lp :)
>
> [snip]
>   It took me a lng time to figure out how to write my code so that 
> when the robot sits exactly on top of the player, there is a message 
> "you have been caught" :-) .  When I run the code, the robot will sit 
> on top of the player and I can have the  message printed - yeaaah!
Awesome, congrats!
> [snip]
> Thanks for this suggestion.  I will likely need to re-write how I 
> check for boundaries.  Currently I was checking for boundaries after I 
> moved the player.  I did this by not letting the player_x and player_y 
> coordinates to be changed if the player was going to go beyond 
> boundaries.  It seems I need to put in a check for boundaries before I 
> move the player.
That should have worked as well.
> Yes, I do want you to comment on the code, absolutely, which I see you 
> so generously did in another email.
 >_>  Yes, I tend to ramble a bit when explaining things.
> Thank you,
> Tonu
That's what I'm here for, all you guys' smiling faces ;)
-Luke

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


[Tutor] adapting a converter openoffice

2007-07-26 Thread Tim Michelsen
Hello,
I am Python learning in an early stage.

I am currently trying to code a converter for openoffice based on 
PyODConverter:
http://www.artofsolving.com/opensource/pyodconverter

My goal is to be able to run my script from anywhere in the system (put 
it in Path) and then convert a file from/to openoffice formats to other 
formats such as doc/pdf etc.

My main problem is how to issue system commands and then run the above 
script.

PyODConverter needs OpenOffice.org to be running as a service which can 
be initiated through the following command on the command line (linux 
shell):
soffice -headless -accept="socket,port=8100;urp;"

once the service is up and running the conversion process is really 
straight forward:
python DocumentConverter.py test.odt test.pdf
where DocumentConverter.py is the ready-to-use converter program 
downloadable at http://www.artofsolving.com/opensource/pyodconverter

I want to be able to convert the files anywhere without the need to 
start the OOo service seperately.

Therefore I tried to add this code on top of the original converter:

###get OOo service started first:
import os
code = os.system('soffice -headless -accept="socket,port=8100;urp;"') # 
Just execute the command, return a success/fail code

when I execute this script nothing happens and I would have to cancel it.

Is there any way to start the OOo service from a python script?

Thanks in advance for your help!

Timmie

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


[Tutor] Extended slicing applied to mapping objects (was What exactly is [::-1]?)

2007-07-26 Thread Bob Gailer
Bob Gailer wrote:
> Alan Gauld wrote:
>   
>> The ref manual ... for extended slicing says:
>>
>> --
>> The semantics for an extended slicing are as follows. The primary must
>> evaluate to a mapping object
>> 
> d = {}
>   
>> It is indexed with a key that is constructed from the slice list, as 
>> follows. 
>> 
> Note that (CORRECTION removed the html tags)
> slice_list ::= slice_item ("," slice_item)* [","]
> slice_item ::= expression | proper_slice  | ellipsis 
>
>   
>> If the slice list contains at least one comma, the key is a tuple containing 
>> the conversion of the slice items
>> 
> d[1,2] = 3
>   
>> otherwise, the conversion of the lone slice item is the key. 
>> 
> This is the usual application of a key where slice_item is an expression
>
> d[313] = 4
>   
>> The conversion of a slice item that is an expression is that expression. The 
>> conversion of an ellipsis slice item is the built-in Ellipsis object. 
>> 
> print d
> {(1, 2): 3, Ellipsis: 4, 313: 4}
>
> Now consider:
>
> slice_item::= expression  | 
> proper_slice  | ellipsis 
> 
>
>
>
> We took care of the cases where slice_item is expression or ellipsis.
>
> How to apply a slice_list consisting of slice_item(s) that are 
> proper_slices to a mapping object???
>
>   


-- 
Bob Gailer
510-978-4454 Oakland, CA
919-636-4239 Chapel Hill, NC


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


Re: [Tutor] Sum of Scores

2007-07-26 Thread bhaaluu
Greetings,

Disclaimer: This source code is written by a Python Newbie.
   Use at your own risk! =)

Here is a snippet that might work for one batter:

#!/usr/bin/env python
# cricket.py
# 2007-07-26
# b h a a l u u at g m a i l dot c o m
import random

def batterUp():
  score=[1,2,3,4,6,'Out']
  totalScore=0
  while 1:
hit=random.choice(score)
if hit != score[-1]:
  totalScore=totalScore+hit
  print "You batted",hit,"Total runs:",totalScore
else:
  totalScore=totalScore+0
  print "You're OUT! Total runs:",totalScore
  break

batterUp()
# end criket.py

Notice that the list, score , has integers and a string in it.
I use the integers to add to the running score, and use the
string 'Out' to stop the while loop. I just did this, and it ran
okay the few times I tried it. YMMV. =)

Happy Programming!
-- 
bhaaluu at gmail dot com

On 7/26/07, Tony Noyeaux <[EMAIL PROTECTED]> wrote:
>
>  The projects are moving along.
>
>  I've created a very simplistic cricket game to learn a few things.
>
>  The user is asked whether to play Aggressive or Defensively.
>
>  Once they pick... a random is picked based on their choice,.. and various
> scores happen until they get out.
>
>  Ignore the realism at this point,.. just getting the basic mechanics
> working first.
>
>  Works fine no problem.
>
>  I want to be able to calculate in the program,.. the total score,.. either
> at each successive score,... or when they finally get out. Not sure how to
> do that at this point.
>
>  So the output would look something like this.
>
>  You Hit a 2, you now have scored 2 runs
>  You hit a 4, you now have scored 6 runs
>  You hit a "Out", you are dismissed for 6 runs total.
>
>  After i get this worked out.. will tweak the actual formulas for the
> randoms, maybe put in multiple outs etc,.. changeable strategy at each out
> etc, and high scores list towards the end.
>
>  First things first,... and the project at hand.
>
>  How do i ... post the totals... as listed above, to the working code below.
>
>
>  Thanks as always
>
>  Tony Noyeaux
>
> -
>  import random
>  score = None
> strat = raw_input("Will you play (a)aggressive or (b)defensive?")
> if strat == "a":
>  while score != "Out":
>   score =
> random.choice(["1","2","3","4","4","6","6","Out","Out","Out","Out"])
>   print score
> else:
>  while score != "Out":
>   score =
> random.choice(["1","1","2","2","3","4","6","Out"])
>   print "You hit a "+score
> --
>
> 
> PC Magazine's 2007 editors' choice for best web mail—award-winning Windows
> Live Hotmail. Check it out!
> ___
> 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] Livewires questions

2007-07-26 Thread Eric Brunson
Tonu Mikk wrote:
> Eric Brunson wrote:
>   
>> Tiger12506 wrote:
>>   
>> 
 Based on your guidance, I figured it out.  I need to use a return 
 statement, which I had not encountered before.  Now I wrote my 
 definitions in this way:

 def collided():
if player_x == robot_x+0.5 and player_y == robot_y+0.5:
   return True
 
   
 
>> Granting that I have not looked at any of the Livewires modules, I just 
>> wanted to say...
>>
>> A general check for collision would probably involve the distance 
>> formula from geometry
>>
>> collided( (x1,y1), (x2,y2) ):
>>return( sqrt( (x1-x2)**2 + (y1-y2)**2 ) < 1 )
>>
>> but could probably be simplified to something like:
>>
>> def collided( (x1,y1), (x2,y2) ):
>>return( abs( x1 - x2 ) < .5 and abs( y1 - y2 ) < .5 )
>>
>>   
>> 
> Thanks Eric for your suggestions.  I believe Livewires modules have 
> simplified collision checking for programming novices like myself.  
> There are two shapes that I am working with, a circle and a square.  The 
> position of the circle is defined by the center coordinates whereas the 
> position of the square is defined by the lower left corner of the 
> square.  When my circle is 0.5 points in diameter, I can add this much 
> to both x and y coordinates of the square which will then give me the 
> point where the square is sitting on top of the circle.  It took me a 
> long time to figure this out.  I had to re-read the Graphics guide sheet 
> that came with Livewires multiple times to try to get it to work 
> correctly.  I believe this part of my code is OK. 
>
>   

Good deal and good luck.



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


Re: [Tutor] Running Python on Gentoo

2007-07-26 Thread Eric Brunson
Greg Lindstrom wrote:
> Eric Brunson wrote:
>   
>> What does the command "which python" say?
>> 
> [EMAIL PROTECTED] ~ $ which python
> /usr/bin/python
>
> HTH,
> --greg
>
>
>   

Wow, Gentoo sucks more than I thought.  ;-)

I can't think of why that wouldn't work, unless you have some odd, 
non-printing character at the end of your interpreter line.

Do other interpreters work?

Try:

#!/usr/bin/perl
print "Perl Sucks!!!\n";

or:

#!/usr/bin/expect
puts "I hate TCL"


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


Re: [Tutor] Pass variable on command line

2007-07-26 Thread Andreas Kostyrka
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Alternatively, I prefer something nicer:

import optparse
p = optparse.OptionParser(usage="%prog [options]")
p.add_option("--list1", action="store_const", const=["blue", "red",
"green"], dest="worklist", help="use the first setting")
p.add_option("--list2", action="store_const", const=["red", "yellow",
"orange"], dest="worklist", help="use the second setting")

opt, args = p.parse_args()
if opt.worklist is None or len(args) != 0:
p.print_help()
raise SystemExit(2)

This looks longer, but gives you a nice commandline parse that does not
bomb out if you do not provide any argument, that is easy to expand, etc.

[caveat: the code above is typed into my mailer, so untested, and from
memory :) ]

Andreas


Terry Carroll wrote:
> On Thu, 26 Jul 2007, jason wrote:
> 
>> Hello,
>>
>> I have a situation where I have 2 lists
>>
>> List1 = ['blue', 'red', green']
>> List2 = ['red', 'yellow', 'orange']
>>
>> And I would like to pass the list name on the command line like so
>>
>> ./test.py List1
>>
>> I know I can get the argument using sys.argv[1]
>>
>> But how can I then use the values in that list inside my program?
> 
> If you must do this, make a dictionary of the lists:
> 
>  d = {"List1": List1, "List2": List2}
> 
> and index into it from your argument:
> 
>  l = d[sys.argv[1]]
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.2 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGqPpoHJdudm4KnO0RAu7AAJwN6Zn4j7XcYQJvLAcEfA6G9l9IngCg4wBt
QqB35uZDGZrSoqvJ+TT/Gww=
=yOcf
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pass variable on command line

2007-07-26 Thread jason

Ok, I see now.  A dictionary using the list elements as values.  This will
work for me.  Thanks!

jason


On 7/26/07, Eric Brunson <[EMAIL PROTECTED]> wrote:


jason wrote:
> Hello,
>
> I have a situation where I have 2 lists
>
> List1 = ['blue', 'red', green']
> List2 = ['red', 'yellow', 'orange']
>
> And I would like to pass the list name on the command line like so
>
> ./test.py List1
>
> I know I can get the argument using sys.argv[1]
>
> But how can I then use the values in that list inside my program?
>
> If I do a VALUES = sys.argv[1], then I get List1 as the values.  I
> want the actual list elements.\\

The easiest way to do this would be to define your lists in a dictionary:


lists = { 'List1': ['blue', 'red', green'], 'List2': ['red', 'yellow',
'orange'] }

if len(sys.argv) > 1 and sys.argv[1] in lists:
   VALUES = lists[sys.argv[1]]


>
> Is this possible?
>
> Thank you
>
> Jason
>
>
>
> 
>
> ___
> 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] Running Python on Gentoo

2007-07-26 Thread Greg Lindstrom
Eric Brunson wrote:
>
> What does the command "which python" say?
[EMAIL PROTECTED] ~ $ which python
/usr/bin/python

HTH,
--greg


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


Re: [Tutor] What exactly is [::-1]?

2007-07-26 Thread Bob Gailer
Alan Gauld wrote:
> The ref manual ... for extended slicing says:
>
> --
> The semantics for an extended slicing are as follows. The primary must
> evaluate to a mapping object
d = {}
> It is indexed with a key that is constructed from the slice list, as follows. 
Note that
slice_list  ::= slice_item  ("," 
slice_item )* [","]

slice_item  ::= expression  | 
proper_slice  | ellipsis 


> If the slice list contains at least one comma, the key is a tuple containing 
> the conversion of the slice items
d[1,2] = 3
> otherwise, the conversion of the lone slice item is the key. 
This is the usual application of a key where slice_item is an expression

d[313] = 4
> The conversion of a slice item that is an expression is that expression. The 
> conversion of an ellipsis slice item is the built-in Ellipsis object. 
print d
{(1, 2): 3, Ellipsis: 4, 313: 4}

Now consider:

slice_item  ::= expression  | 
proper_slice  | ellipsis 




We took care of the cases where slice_item is expression or ellipsis.

How to apply a slice_list consisting of slice_item(s) that are 
proper_slices to a mapping object???

-- 
Bob Gailer
510-978-4454 Oakland, CA
919-636-4239 Chapel Hill, NC


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


Re: [Tutor] What exactly is [::-1]?

2007-07-26 Thread Chris Calloway
Kent Johnson wrote:
> AFAIK extended slicing is not supported by any standard Python data 
> types, it was added specifically for Numeric.

Numeric *is* responsible for getting *one* of the two forms of extended 
slicing added (the one with multiple slices or ellipses separated by 
commas) and yes, that *one form* isn't supported by any builtin or 
"standard" global module Python data types.

The *other* form of extended slicing, the one with two colons (and no 
commas) is supported by typeseq objects, though.

The phrase "extended slicing" probably ought to be clarified in the 
documentation as having two distinct forms (stepped and multiple). This 
is a root of considerable confusion for people reading about extended 
slicing in the standard documentation.

Extended slicing is really talking about two ways of creating a *slice 
object* (and there are other ways of creating slice objects). And not 
all slice objects are created equally as far as typeseq and array module 
objects are concerned.

A sensible solution would be to refer to the stepped form as a simple 
slice and realize that both "stepped simple" slices and comma-extended 
slices create slice objects in Python 2.3 and later. I don't know how 
wise it would be to further confuse the issue by changing the 
documentation at this point. It's a judgment call.

Using stepped slicing with numpy/Numeric/numarray style arrays is also 
very different from using it with the standard array module and typeseq 
objects.

With typeseq objects, the two colon extended slicing provides a reversed 
*copy* of the typeseq object as opposed to the .reverse method which 
reverses a typeseq object *in place* (and has no return value):

 >>> a = [0,1,2,3,4]
 >>> b = a[::-1]
 >>> a[2] = 6
 >>> a.reverse()
 >>> a
[4, 3, 6, 1, 0]
 >>> b
[4, 3, 2, 1, 0]
 >>>

Same with the array module (a copy is made):

 >>> import array
 >>> e = array.array('i',[0,1,2,3,4])
 >>> f = e[::-1]
 >>> e[2] = 23
 >>> e.reverse()
 >>> e
array('i', [4, 3, 23, 1, 0])
 >>> f
array('i', [4, 3, 2, 1, 0])
 >>>

However, with numpy/Numeric/numarray style arrays, extended slicing 
gives you a "view" of the original array, somewhat similar to using 
.reverse() on typeseq objects (but still different because the original 
array is unchanged). Changes to the original array will be *reflected* 
in the view objects of that original array (unlike in the example copied 
objects above):

 >>> import numpy
 >>> c = numpy.array([0, 1, 2, 3, 4])
 >>> d = c[::-1]
 >>> c[2] = 9
 >>> c
array([0, 1, 9, 3, 4])
 >>> d
array([4, 3, 9, 1, 0])
 >>>

To get a reversed *copy* of numpy/Numeric/numarray style arrays, you'll 
need to use their .copy() method on the extended slice. 
numpy/Numeric/numarray style arrays have no .reverse() method as typeseq 
and array module objects do:

 >>> g = c[::-1].copy()
 >>> c[2] = 42
 >>> c
array([ 0,  1, 42,  3,  4])
 >>> g
array([4, 3, 9, 1, 0])
 >>> c.reverse()
Traceback (most recent call last):
   File "", line 1, in ?
AttributeError: 'numpy.ndarray' object has no attribute 'reverse'
 >>>

So that extended slicing of the form [::-1] is kind of necessary with 
numpy/Numeric/numarray style arrays in order to "reverse" the object. 
Just remember, double colon extended slicing has a different effect on 
typeseq and array module objects (by making a copy).

-- 
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] Pass variable on command line

2007-07-26 Thread Terry Carroll
On Thu, 26 Jul 2007, jason wrote:

> Hello,
> 
> I have a situation where I have 2 lists
> 
> List1 = ['blue', 'red', green']
> List2 = ['red', 'yellow', 'orange']
> 
> And I would like to pass the list name on the command line like so
> 
> ./test.py List1
> 
> I know I can get the argument using sys.argv[1]
> 
> But how can I then use the values in that list inside my program?

If you must do this, make a dictionary of the lists:

 d = {"List1": List1, "List2": List2}

and index into it from your argument:

 l = d[sys.argv[1]]



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


Re: [Tutor] Running Python on Gentoo

2007-07-26 Thread Eric Brunson

What does the command "which python" say?

Khamid Nurdiev wrote:
> Yes, I have the same problem with running python scripts from console 
> in Debian, the line "#! /usr/bin/python" doesn't help. I have to type 
> "python script.py" in order to run the script.py file.
>
> On 7/26/07, *Greg Lindstrom* <[EMAIL PROTECTED] 
> > wrote:
>
> Hello,
> I am running python 2.4.2 on Gentoo Unix and am having problems
> running
> programs.  I have a script, hello.py as such:
>
> #! /usr/bin/python
> print 'hello, world'
>
> that I save and add executable permission.  Then at the prompt I
> type in..
>
> $ ./hello.py
> -bash: ./hello.py: /usr/bin/python: bad interpreter: Permission denied
>
> If I type
> $ python hello.py
> I get "hello, world" as expected.
>
> I was hoping that the "shabang" would have the script execute.  Am I
> missing something?  Can you help me?  BTW, when I type /usr/bin/python
> at the prompt I get the python interpreter, so at least that's
> working.
>
> Thanks,
> --greg
>
> ___
> 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 maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pass variable on command line

2007-07-26 Thread Eric Brunson
jason wrote:
> Hello,
>  
> I have a situation where I have 2 lists
>  
> List1 = ['blue', 'red', green']
> List2 = ['red', 'yellow', 'orange']
>  
> And I would like to pass the list name on the command line like so
>  
> ./test.py List1
>  
> I know I can get the argument using sys.argv[1]
>  
> But how can I then use the values in that list inside my program?
>  
> If I do a VALUES = sys.argv[1], then I get List1 as the values.  I 
> want the actual list elements.\\

The easiest way to do this would be to define your lists in a dictionary:


lists = { 'List1': ['blue', 'red', green'], 'List2': ['red', 'yellow', 
'orange'] }

if len(sys.argv) > 1 and sys.argv[1] in lists:
VALUES = lists[sys.argv[1]]


>  
> Is this possible?
>  
> Thank you
>  
> Jason
>  
>  
>  
> 
>
> ___
> 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] Thanks re: [::-1]

2007-07-26 Thread Chris Calloway
Charles Cuell wrote:
> The one odd thing about Python's slice notation is that the -1 means to
> start from the end and work backwards.  My first inclination would have
> been to assume that -1 means to start at i and go to j by steps of -1
> (only nonempy if j < i).

A negative step attribute does not change the semantics of the start and 
stop (read only) attributes of slice objects:

 >>> m = range(10)
 >>> m[2:7:-1]
[]
 >>> m[7:2:-1]
[7, 6, 5, 4, 3]
 >>> m[-3:-8:-1]
[7, 6, 5, 4, 3]
 >>>

So your first inclination was correct! :)

i does go to j by steps of k.

-- 
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] Running Python on Gentoo

2007-07-26 Thread Khamid Nurdiev
Yes, I have the same problem with running python scripts from console in
Debian, the line "#! /usr/bin/python" doesn't help. I have to type "python
script.py" in order to run the script.py file.

On 7/26/07, Greg Lindstrom <[EMAIL PROTECTED]> wrote:
>
> Hello,
> I am running python 2.4.2 on Gentoo Unix and am having problems running
> programs.  I have a script, hello.py as such:
>
> #! /usr/bin/python
> print 'hello, world'
>
> that I save and add executable permission.  Then at the prompt I type in..
>
> $ ./hello.py
> -bash: ./hello.py: /usr/bin/python: bad interpreter: Permission denied
>
> If I type
> $ python hello.py
> I get "hello, world" as expected.
>
> I was hoping that the "shabang" would have the script execute.  Am I
> missing something?  Can you help me?  BTW, when I type /usr/bin/python
> at the prompt I get the python interpreter, so at least that's working.
>
> Thanks,
> --greg
>
> ___
> 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] Livewires questions

2007-07-26 Thread Tonu Mikk
Eric Brunson wrote:
> Tiger12506 wrote:
>   
>>> Based on your guidance, I figured it out.  I need to use a return 
>>> statement, which I had not encountered before.  Now I wrote my 
>>> definitions in this way:
>>>
>>> def collided():
>>>if player_x == robot_x+0.5 and player_y == robot_y+0.5:
>>>   return True
>>> 
>>>   
>
> Granting that I have not looked at any of the Livewires modules, I just 
> wanted to say...
>
> A general check for collision would probably involve the distance 
> formula from geometry
>
> collided( (x1,y1), (x2,y2) ):
>return( sqrt( (x1-x2)**2 + (y1-y2)**2 ) < 1 )
>
> but could probably be simplified to something like:
>
> def collided( (x1,y1), (x2,y2) ):
>return( abs( x1 - x2 ) < .5 and abs( y1 - y2 ) < .5 )
>
>   
Thanks Eric for your suggestions.  I believe Livewires modules have 
simplified collision checking for programming novices like myself.  
There are two shapes that I am working with, a circle and a square.  The 
position of the circle is defined by the center coordinates whereas the 
position of the square is defined by the lower left corner of the 
square.  When my circle is 0.5 points in diameter, I can add this much 
to both x and y coordinates of the square which will then give me the 
point where the square is sitting on top of the circle.  It took me a 
long time to figure this out.  I had to re-read the Graphics guide sheet 
that came with Livewires multiple times to try to get it to work 
correctly.  I believe this part of my code is OK. 

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


[Tutor] Pass variable on command line

2007-07-26 Thread jason

Hello,

I have a situation where I have 2 lists

List1 = ['blue', 'red', green']
List2 = ['red', 'yellow', 'orange']

And I would like to pass the list name on the command line like so

./test.py List1

I know I can get the argument using sys.argv[1]

But how can I then use the values in that list inside my program?

If I do a VALUES = sys.argv[1], then I get List1 as the values.  I want the
actual list elements.

Is this possible?

Thank you

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


[Tutor] Running Python on Gentoo

2007-07-26 Thread Greg Lindstrom
Hello,
I am running python 2.4.2 on Gentoo Unix and am having problems running 
programs.  I have a script, hello.py as such:

#! /usr/bin/python
print 'hello, world'

that I save and add executable permission.  Then at the prompt I type in..

$ ./hello.py
-bash: ./hello.py: /usr/bin/python: bad interpreter: Permission denied

If I type
$ python hello.py
I get "hello, world" as expected.

I was hoping that the "shabang" would have the script execute.  Am I 
missing something?  Can you help me?  BTW, when I type /usr/bin/python 
at the prompt I get the python interpreter, so at least that's working.

Thanks,
--greg

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


Re: [Tutor] Livewires questions

2007-07-26 Thread Eric Brunson
Tonu Mikk wrote:
> Tiger12506 wrote:
>   
>>> Based on your guidance, I figured it out.  I need to use a return 
>>> statement, which I had not encountered before.  Now I wrote my 
>>> definitions in this way:
>>>
>>> def collided():
>>>if player_x == robot_x+0.5 and player_y == robot_y+0.5:
>>>   return True
>>> 
>>>   
>>  
>> This could be simplified more.
>> Here's an example as a hint. These two functions are the same.
>>
>> def f():
>>   if a == b and c == d:
>> return True
>>
>> def g():
>>   return (a==b and c == d)
>>
>>   
>> 
> I got it.  I will do it like this:
> def collided():
> return (player_x == robot_x+0.5 and player_y == robot_y+0.5)
>
>   

I believe that will only work if the robot collides with the player from 
the southeast.

I'm not sure of the rules of the game, but if that's not the case, then 
see my previous note.


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


Re: [Tutor] Livewires questions

2007-07-26 Thread Eric Brunson
Tiger12506 wrote:
>> Based on your guidance, I figured it out.  I need to use a return 
>> statement, which I had not encountered before.  Now I wrote my 
>> definitions in this way:
>>
>> def collided():
>>if player_x == robot_x+0.5 and player_y == robot_y+0.5:
>>   return True
>> 

Granting that I have not looked at any of the Livewires modules, I just 
wanted to say...

A general check for collision would probably involve the distance 
formula from geometry

collided( (x1,y1), (x2,y2) ):
   return( sqrt( (x1-x2)**2 + (y1-y2)**2 ) < 1 )

but could probably be simplified to something like:

def collided( (x1,y1), (x2,y2) ):
   return( abs( x1 - x2 ) < .5 and abs( y1 - y2 ) < .5 )

>  
> This could be simplified more.
> Here's an example as a hint. These two functions are the same.
>
> def f():
>   if a == b and c == d:
> return True
>
> def g():
>   return (a==b and c == d)
>
>
>   
>> Then I use that value in another definition like this:
>>
>> def check_collisions():
>>if collided() == 1:
>>   print "You have been caught"
>> 
>
> And ~
>
> if collided():
>   print "You have been caught"
>   
> ___
> 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] Livewires questions

2007-07-26 Thread Tonu Mikk
Tiger12506 wrote:
>> Based on your guidance, I figured it out.  I need to use a return 
>> statement, which I had not encountered before.  Now I wrote my 
>> definitions in this way:
>>
>> def collided():
>>if player_x == robot_x+0.5 and player_y == robot_y+0.5:
>>   return True
>> 
>  
> This could be simplified more.
> Here's an example as a hint. These two functions are the same.
>
> def f():
>   if a == b and c == d:
> return True
>
> def g():
>   return (a==b and c == d)
>
>   
I got it.  I will do it like this:
def collided():
return (player_x == robot_x+0.5 and player_y == robot_y+0.5)

Thank you,
Tonu

-- 
Tonu Mikk
Educational Technology Consultant
Digital Media Center - dmc.umn.edu
[EMAIL PROTECTED] 612 625-9221

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


Re: [Tutor] Livewires questions

2007-07-26 Thread Tiger12506
> Based on your guidance, I figured it out.  I need to use a return 
> statement, which I had not encountered before.  Now I wrote my 
> definitions in this way:
> 
> def collided():
>if player_x == robot_x+0.5 and player_y == robot_y+0.5:
>   return True
 
This could be simplified more.
Here's an example as a hint. These two functions are the same.

def f():
  if a == b and c == d:
return True

def g():
  return (a==b and c == d)


> Then I use that value in another definition like this:
> 
> def check_collisions():
>if collided() == 1:
>   print "You have been caught"

And ~

if collided():
  print "You have been caught"
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Thanks re: [::-1]

2007-07-26 Thread Charles Cuell
Thanks to everybody that worked to clarify the meaning of [::-1].

My main concern was that it looked like the notation came out of nowhere
and, as such, was inconsistent with the usual slice notation.  The
documentation did make it clear, since the full slicing notation is
s[i:j:k], leaving out the i and j to indicate starting at the
beginning and stopping at the end results in s[::k].

The one odd thing about Python's slice notation is that the -1 means to
start from the end and work backwards.  My first inclination would have
been to assume that -1 means to start at i and go to j by steps of -1
(only nonempy if j < i).

Thanks again.

Charles Cuell
[EMAIL PROTECTED]



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


Re: [Tutor] Livewires questions

2007-07-26 Thread Tonu Mikk
Luke, thank you for your quick and complete response.  Based on your 
suggestions I have already made some progress!  BTW, I am so glad that I 
can ask this list my Python questions and get help.  I began feeling 
quite stuck and not knowing where to turn for help.  So, thank you for 
the great service!

Luke Paireepinart wrote:
> Tonu Mikk wrote:
>> Thanks for offering to help!  I am following the Livewires exercise 
>> (attached file "5-robots.pdf").  I have gotten as far as page 7.  
>> Attached is also my code so far in robotsarecoming-teleport.py.
>> Question 1.  I was checking for collision of a robot and player first 
>> in this way:
>>
>> def check_collisions():
>>if player_x == robot_x+0.5 and player_y == robot_y+0.5:
>>   print 'You have been caught'
>>
>> This was working fine.  I then tried to create a definition like this:
>>
>> def collided():
>>player_x == robot_x+0.5 and player_y == robot_y+0.5
> I haven't looked at your code yet, but this doesn't seem like a very 
> good way to check for collisions,
> unless the player moves on a grid of 0.5 at a time, and you guarantee 
> that you can check if the player collided with a robot on every move.
> even so, doesn't this only collide with the robot if the player hits 
> the bottom-right corner?
Yes, this indeed looks strange.  I believe it is particular to this 
Livewires exercise.  The reason it is strange is that I am comparing a 
position of two different shapes, a circle and a square.  The position 
for the circle is in the center of the circle and it is defined by 
player_x and player_y coordinates.  The position of the square is 
defined by the first two coordinates that make up a square robot_x and 
robot_y.  The circle radius is 0.5.  It took me a lng time to figure 
out how to write my code so that when the robot sits exactly on top of 
the player, there is a message "you have been caught" :-) .  When I run 
the code, the robot will sit on top of the player and I can have the  
message printed - yeaaah!
>
>>
>> and then check for collisions in this way (as in my code):
>> def check_collisions():
>>if collided() == 1:
>>print 'You have been caught'
> The reason this isn't working is because your function 'collided' 
> doesn't return anything.
> Consider this example:
>
> def foo():
>"Hello"
>
> What do you expect to happen when you call foo()?
> 1) "Hello" won't be printed, because there is no 'print' statement here.
> 2) "Hello" won't be returned, because you have no return statement.
> So what does happen, then?
> well, foo() creates a string in memory with "Hello" stored in it, but 
> there are no variables referenced to it, so nothing happens.
> Basically, the only thing foo() accomplishes is that it wastes memory 
> until "Hello" is garbage collected and deleted.
>
> Now consider this:
> def foo():
>a == b and b == c
>
> What do you expect to happen here?
> It's similar to the above example.
> a == b is evaluated.
> if it's true, b == c is evaluated.
> if it's true, then the value True is there, but it's not assigned to 
> any variables, so it just disappears.
> Can you see now why your code doesn't work?
>
> Here's an example of a function you'd want to look at to give you an 
> idea of what to do:
>
> def foo():
>  return a < b
>> But this isn't printing out anything when the player and robot 
>> collide.  I think I need to pass a variable of collided somehow, but 
>> I am not sure how.  I also tried following:
>> def check_collisions():
>>if collided()
>>   print 'You have been caught'
>> but this isn't working either.
> This is because collided() is not returning anything.
> Try this:
> print collided()
> you will get this output:
> None
Based on your guidance, I figured it out.  I need to use a return 
statement, which I had not encountered before.  Now I wrote my 
definitions in this way:

def collided():
if player_x == robot_x+0.5 and player_y == robot_y+0.5:
   return True

Then I use that value in another definition like this:

def check_collisions():
if collided() == 1:
   print "You have been caught"

Which is displaying the message when the robot sits on top of the player.
   
>>
>> Question 2.  I created a if statement to check if the "t" key is 
>> pressed on a keyboard.  If it is, I want the player to be placed on 
>> another location on the grid.  However nothing happens when I press 
>> the "t" key.  I am not sure why.
> Instead of changing the player's location, print "YOU PRESSED T" 
> instead, and if you see that in the console, you know there's a 
> problem with your repositioning code.  If you don't see that, you know 
> it's a problem with your input code.
> If you can't diagnose further than that, let us know.
It is great suggestion to use a print statement for testing!  I tried it 
and I did not get a printed message either.  I will need to think about 
it some more.  I believe your other email will give me some ideas here.
>>
>> Question 3.  I thin

Re: [Tutor] while Loop

2007-07-26 Thread Mike Hansen
> -Original Message-
> Subject: Re: [Tutor] while Loop
> 
> Oops, didn't notice the uppercase U, thanks Luke.
> 
> - Original Message - 
> Subject: Re: [Tutor] while Loop
> 
> 
> >> define it with usedPocketsOne = 192000?
> > no, I said UsedPocketsOne was not defined.  Note the 
> different starting 
> > letter.
> > Python is case senstitive, meaning usedPocketsOne is not 
> the same as 
> > UsedPocketsOne.
> > So yes, you defined usedPocketsOne with the assignment to 
> 192000, but 
> > you did not define UsedPocketsOne.
> > 

I've been out of the office for the last week, so I'm catching up.

You might use something like PyChecker, PyLint, or PyFlakes. Those
utilities would catch errors like this.

I have a hotkey in VIM that kicks off PyFlakes on the current buffer. 

Also, I'm not 100% sure, but I think Komodo IDE would catch this as
well.

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


Re: [Tutor] Finding the caller

2007-07-26 Thread jay
Thanks Kent and Andreas

That is exactly what I needed!  Very nice indeed...

jay


On 7/26/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> jay wrote:
> > Hello all,
> >
> > If I import a module, which has a bunch of simple functions in it, is
> > there an easy way to find the direct caller from inside one of those
> > functions?  I'm looking to know which script has imported and thus
> > called the library function.  Thanks!
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062
>
> Kent
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Finding the caller

2007-07-26 Thread Kent Johnson
jay wrote:
> Hello all,
>  
> If I import a module, which has a bunch of simple functions in it, is 
> there an easy way to find the direct caller from inside one of those 
> functions?  I'm looking to know which script has imported and thus 
> called the library function.  Thanks!

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062

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


Re: [Tutor] Finding the caller

2007-07-26 Thread Andreas Kostyrka
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

sys._getframe.

Andreas

jay wrote:
> Hello all,
>  
> If I import a module, which has a bunch of simple functions in it, is
> there an easy way to find the direct caller from inside one of those
> functions?  I'm looking to know which script has imported and thus
> called the library function.  Thanks!
>  
> jay
>  
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.2 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGqLZeHJdudm4KnO0RAkV+AJ42mi3wqHp3vX1IBOQVeqIIiS7E7ACdHeRV
E/oiSDLtQ408sNFQCIorMWo=
=zY8c
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Finding the caller

2007-07-26 Thread jay
Hello all,

If I import a module, which has a bunch of simple functions in it, is there
an easy way to find the direct caller from inside one of those functions?
I'm looking to know which script has imported and thus called the library
function.  Thanks!

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


[Tutor] Sum of Scores

2007-07-26 Thread Tony Noyeaux

The projects are moving along.
 
I've created a very simplistic cricket game to learn a few things.
 
The user is asked whether to play Aggressive or Defensively.
 
Once they pick... a random is picked based on their choice,.. and various 
scores happen until they get out.
 
Ignore the realism at this point,.. just getting the basic mechanics working 
first.
 
Works fine no problem.
 
I want to be able to calculate in the program,.. the total score,.. either at 
each successive score,... or when they finally get out. Not sure how to do that 
at this point.
 
So the output would look something like this.
 
You Hit a 2, you now have scored 2 runs
You hit a 4, you now have scored 6 runs
You hit a "Out", you are dismissed for 6 runs total.
 
After i get this worked out.. will tweak the actual formulas for the randoms, 
maybe put in multiple outs etc,.. changeable strategy at each out etc, and high 
scores list towards the end.
 
First things first,... and the project at hand.
 
How do i ... post the totals... as listed above, to the working code below.
 
 
Thanks as always
 
Tony Noyeaux
 
-
import random
score = Nonestrat = raw_input("Will you play (a)aggressive or (b)defensive?")if 
strat == "a": while score != "Out":  score = 
random.choice(["1","2","3","4","4","6","6","Out","Out","Out","Out"])   print 
scoreelse: while score != "Out":  score = 
random.choice(["1","1","2","2","3","4","6","Out"])  print "You hit a "+score
--
_
PC Magazine’s 2007 editors’ choice for best web mail—award-winning Windows Live 
Hotmail.
http://imagine-windowslive.com/hotmail/?locale=en-us&ocid=TXT_TAGHM_migration_HMWL_mini_pcmag_0707___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What exactly is [::-1]?

2007-07-26 Thread Kent Johnson
Alan Gauld wrote:
> "wesley chun" <[EMAIL PROTECTED]> wrote
> 
>> when you use the 3rd element, it's called the extended slice syntax.
> 
> The ref manual describes use of the third value as simple slicing,
> for extended slicing it says this:



> I've read it three times now and stioll have no idea what its on 
> about!

Extended slicing is used by Numeric and its successors to slice 
multi-dimensional arrays on multiple dimensions. An extended slice is a 
simple slice for each dimension of the array, separated by commas. See
http://numpy.scipy.org/numpydoc/numpy-6.html#pgfId-36074

AFAIK extended slicing is not supported by any standard Python data 
types, it was added specifically for Numeric.

When an object is indexed with an extended slice, the object's 
__getitem__() method is passed a tuple of slice objects. It's then up to 
the object to make sense of it:

In [1]: class ext(object):
...: def __getitem__(self, key):
...: print repr(key)
...:
...:
In [2]: e=ext()
In [3]: e[3]
3
In [4]: e[1:4]
slice(1, 4, None)
In [5]: e[1:4,2:5]
(slice(1, 4, None), slice(2, 5, None))

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


Re: [Tutor] What exactly is [::-1]?

2007-07-26 Thread Alan Gauld

"Dick Moores" <[EMAIL PROTECTED]> wrote

>>Not sure why it didn't help you Dick, but it led me to:
>>
>>http://docs.python.org/lib/typesseq.html
>>
>
> Alan, I don't see an explanation of [::-1] anywhere in those 3 
> links.
> There needs to be a clear description and better examples somewhere
> in the docs, IMO.

I agree the explanation is 'terse' but it does explain that the syntax
is S[i:j:k] and that any/all of the values can be ommitted and what 
their
defaults are. It also explains the significance of -1 as a value.


So [::-1] is simply i, j  taking defaults and -1 for k

So its equivalent to S[0:len(S):-1]

But I agree there could be a few more examples of the use of
the k element.


-- 
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] What exactly is [::-1]?

2007-07-26 Thread Dick Moores
At 12:17 AM 7/26/2007, Alan Gauld wrote:

>"Dick Moores" <[EMAIL PROTECTED]> wrote
>
> >>I could send you a link but I'd just google 'python list slicing' to
> >>find it, so I'll leave that as an exercise for the reader.
> >
> > I don't find Google of help with this. Could someone supply a link?
>
>Not sure why it didn't help you Dick, but it led me to:
>
>http://docs.python.org/lib/typesseq.html
>
>Which is admittedly sparing in its explanation but does at
>least describe the three values involved and their defaults.
>
>The tutorial also threw up this:
>
>http://docs.python.org/tut/node5.html
>
>Which describes basic slicing (using only 2 indices) of strings
>and also has a link to the previous reference page.
>
>Finally I tried googling for 'python slicing' and got this as my first
>hit:
>
>http://docs.python.org/ref/slicings.html
>
>Which is the language lawyers version!

Alan, I don't see an explanation of [::-1] anywhere in those 3 links. 
There needs to be a clear description and better examples somewhere 
in the docs, IMO.

My thanks to Luke and Wesley.

Dick


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


Re: [Tutor] What exactly is [::-1]?

2007-07-26 Thread Alan Gauld

"wesley chun" <[EMAIL PROTECTED]> wrote

> when you use the 3rd element, it's called the extended slice syntax.

The ref manual describes use of the third value as simple slicing,
for extended slicing it says this:

--
 The semantics for an extended slicing are as follows. The primary 
must
evaluate to a mapping object, and it is indexed with a key that is 
constructed
from the slice list, as follows. If the slice list contains at least 
one comma,
the key is a tuple containing the conversion of the slice items; 
otherwise,
the conversion of the lone slice item is the key. The conversion of a 
slice
item that is an expression is that expression. The conversion of an 
ellipsis
slice item is the built-in Ellipsis object. The conversion of a proper 
slice
is a slice object (see section 3.2) whose start, stop and step 
attributes
are the values of the expressions given as lower bound, upper bound 
and
stride, respectively, substituting None for missing expressions.
---

I've read it three times now and stioll have no idea what its on 
about!

Some ex[erimentation needed I think, but no time now.

:-)

-- 
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] What exactly is [::-1]?

2007-07-26 Thread Alan Gauld

"Luke Paireepinart" <[EMAIL PROTECTED]> wrote

> well, some experimentation leads me to believe this is the syntax 
> for
> list slicing:

The referemnce link I poosted gives the exact syntax plus this 
description:

--
 The semantics for a simple slicing are as follows. The primary must 
evaluate
to a sequence object. The lower and upper bound expressions, if 
present,
must evaluate to plain integers; defaults are zero and the sys.maxint,
respectively. If either bound is negative, the sequence's length is 
added to it.
The slicing now selects all items with index k such that i <= k < j 
where
i and j are the specified lower and upper bounds. This may be an empty
sequence. It is not an error if i or j lie outside the range of valid 
indexes
(such items don't exist so they aren't selected).


For s[i:j:k}

where the primary is i, the secondary j and the index k...

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] What exactly is [::-1]?

2007-07-26 Thread Alan Gauld

"Dick Moores" <[EMAIL PROTECTED]> wrote

>>I could send you a link but I'd just google 'python list slicing' to
>>find it, so I'll leave that as an exercise for the reader.
>
> I don't find Google of help with this. Could someone supply a link?

Not sure why it didn't help you Dick, but it led me to:

http://docs.python.org/lib/typesseq.html

Which is admittedly sparing in its explanation but does at
least describe the three values involved and their defaults.

The tutorial also threw up this:

http://docs.python.org/tut/node5.html

Which describes basic slicing (using only 2 indices) of strings
and also has a link to the previous reference page.

Finally I tried googling for 'python slicing' and got this as my first 
hit:

http://docs.python.org/ref/slicings.html

Which is the language lawyers version!

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