pygame: output to file?

2012-04-16 Thread superpollo

HI.

is there a way to convert the graphical output of a pygame application 
to a mpeg file or better an animated gif? i mean, not using an external 
capture program...


bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: pygame: output to file?

2012-04-16 Thread superpollo

alex23 ha scritto:

On Apr 16, 7:34 pm, superpollo  wrote:

is there a way to convert the graphical output of a pygame application
to a mpeg file or better an animated gif? i mean, not using an external
capture program...


There is, but it's probably not going to be as performant as using
something external:

http://stackoverflow.com/questions/6087484/how-to-capture-pygame-screen


but where in the code should i put the line:

pygame.image.save(window, "screenshot.jpeg")

?

tia

bye

--
http://mail.python.org/mailman/listinfo/python-list


Re: pygame: output to file?

2012-04-16 Thread superpollo

superpollo ha scritto:

alex23 ha scritto:

On Apr 16, 7:34 pm, superpollo  wrote:

is there a way to convert the graphical output of a pygame application
to a mpeg file or better an animated gif? i mean, not using an external
capture program...


There is, but it's probably not going to be as performant as using
something external:

http://stackoverflow.com/questions/6087484/how-to-capture-pygame-screen


but where in the code should i put the line:

pygame.image.save(window, "screenshot.jpeg")


i mean, if i would want to capture ALL the frames in a video file...

i ask this becase this line captures just one frame and overwrites over 
the successive ones...


bye
--
http://mail.python.org/mailman/listinfo/python-list


simple cgi program

2010-01-17 Thread superpollo

hi clp.

i would like to submit the following code for review. it is a simple 
common gateway interface program, which uses the least possible 
libraries for the sake of mechanism undertanding.


the third option in the firts conditional is for commandline testing.

bye.



code follows as:

#!/usr/bin/env python
import sys
import os
import urllib as url
me = os.path.basename(sys.argv[0])
env = os.environ
method = "POST"
data=None
if env.get("REQUEST_METHOD") == "GET":
data = env.get("QUERY_STRING")
elif env.get("REQUEST_METHOD") == "POST":
data = sys.stdin.read(int(env.get("CONTENT_LENGTH")))
elif not env.get("REQUEST_METHOD"):
data = sys.stdin.readline().rstrip("\n")
if not data:
sys.stdout.write("Content-type: text/html\n\n")
sys.stdout.write("\n" % (me , method))
sys.stdout.write("TYPE A DIGIT SEQUENCE AND HIT [ENTER]:\n")
sys.stdout.write("\n")
sys.stdout.write("\n")
else:
name = data.partition("=")[0]
encvalue = data.partition("=")[2]
decvalue = url.unquote_plus(encvalue)
sys.stdout.write("Content-type: text/plain\n\n")
sys.stdout.write("method: %s\n" % method)
sys.stdout.write("data: %s\n" % data)
sys.stdout.write("name: %s\n" % name)
sys.stdout.write("encvalue: %s\n" % encvalue)
sys.stdout.write("decvalue: %s\n" % decvalue)
if decvalue.isdigit():
sys.stdout.write("the sequence you typed is: %s\n" % decvalue)
else:
sys.stdout.write("what you typed is not a valid sequence\n")



criticism and advice are appreciated!
--
http://mail.python.org/mailman/listinfo/python-list


Re: simple cgi program

2010-01-17 Thread superpollo

D'Arcy J.M. Cain ha scritto:

On Sun, 17 Jan 2010 15:15:12 +0100
superpollo  wrote:

hi clp.

i would like to submit the following code for review. it is a simple 
common gateway interface program, which uses the least possible 
libraries for the sake of mechanism undertanding.


Why not just use the cgi module?  It does all that for you.



yes, but i am trying to learn exactly the cgi mechanism internals, just 
for fun ;-)


--
http://mail.python.org/mailman/listinfo/python-list


Re: substitution

2010-01-18 Thread superpollo

superpollo ha scritto:

hi.

what is the most pythonic way to substitute substrings?

eg: i want to apply:

foo --> bar
baz --> quux
quuux --> foo

so that:

fooxxxbazyyyquuux --> barxxxquuxyyyfoo

bye


i explain better:

say the subs are:

quuux --> foo
foo --> bar
baz --> quux

then i cannot apply the subs in sequence (say, .replace() in a loop), 
otherwise:


fooxxxbazyyyquuux --> fooxxxbazyyyfoo --> barxxxbazyyybar --> 
barxxxquuxyyybar


not as intended...
--
http://mail.python.org/mailman/listinfo/python-list


substitution

2010-01-18 Thread superpollo

hi.

what is the most pythonic way to substitute substrings?

eg: i want to apply:

foo --> bar
baz --> quux
quuux --> foo

so that:

fooxxxbazyyyquuux --> barxxxquuxyyyfoo

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: substitution

2010-01-18 Thread superpollo
it looked simpler when i posted, but i realize that the problem is non 
trivial.


thanks to everybody.

i guess that the algorithm would be easier if it was known in advance 
that the string to substitute must have some specific property, say:


1) they all must start with "XYZ"
2) they all have the same length N (e.g. 5)

like this:

qweXYZ12asdXYZ1345XYZ ---> qweIWAS12asdIWAS1345XYZ

bye
--
http://mail.python.org/mailman/listinfo/python-list


not and is not problem

2010-01-18 Thread superpollo

hi:

#!/usr/bin/env python
data = "seq=123"
name , value = data.split("=")
print name
print value
if not name == "seq":
print "DOES NOT PRINT OF COURSE..."
if name is not "seq":
print "WTF! WHY DOES IT PRINT?"

help please.

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is a list compression in Python?

2010-01-18 Thread superpollo

Kit ha scritto:

Hello Everyone, I am not sure if I have posted this question in a
correct board. Can anyone please teach me:

What is a list compression in Python?

Would you mind give me some list compression examples?


Thanks & really appreciate that.
Kit


i think that's compreHENsion...

http://www.python.org/doc/2.5.4/tut/node7.html#SECTION00714
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Data Plotting Library DISLIN 10.0

2010-01-19 Thread superpollo

Helmut Michels ha scritto:

Dear Pytnon users,

I am pleased to announce version 10.0 of the data plotting software
DISLIN.


why dont you make it free software (i mean. GPL'ed)

bye
--
http://mail.python.org/mailman/listinfo/python-list


off topic but please forgive me me and answer

2010-04-01 Thread superpollo

how much is one half times one half?
--
http://mail.python.org/mailman/listinfo/python-list


Re: off topic but please forgive me me and answer

2010-04-03 Thread superpollo

Patrick Maupin ha scritto:

On Apr 2, 2:41 pm, Andreas Waldenburger 
wrote:


While everyone else is mocking you: Can you please elaborate on why you
want to know and what kind of problem you're trying to solve with this?
Also, don't you think you should have picked a maths forum for this
kind of question?


Methinks the OP is fluent in the way of choosing newsgroups.
According to google, he has posted 6855 messages in 213 groups.

http://groups.google.com/groups/profile?enc_user=ul3SQhIYmLD0Oj5Yxp-liP3Vw9uApbyajUBv9M9XLUB2gqkZmQ

And I can't speak for anybody else, but I just assumed it was an April
Fool's question.  I meant to be laughing with the OP, not at him, so
sorry if I misunderstood.


no no you understood prfectly *but* the thing is i am a regular in an 
italian language math ng which is haunted by a crackpot who insists that 
1/2 * 1/2 cannot be 1/4, "because multiplication means getting bigger", 
so i took a semi-serious stance and made a few posts as a statistical 
tentative to "convince" said crackpot that the world is not going crazy 
(but maybe he is)


thanks

ps: note that my nickname is not unique, and there are a few people 
whith the same one... and i didn't ever post using googlegroups

--
http://mail.python.org/mailman/listinfo/python-list


Re: off topic but please forgive me me and answer

2010-04-03 Thread superpollo

Steve Holden ha scritto:

superpollo wrote:

Patrick Maupin ha scritto:

On Apr 2, 2:41 pm, Andreas Waldenburger 
wrote:


While everyone else is mocking you: Can you please elaborate on why you
want to know and what kind of problem you're trying to solve with this?
Also, don't you think you should have picked a maths forum for this
kind of question?

Methinks the OP is fluent in the way of choosing newsgroups.
According to google, he has posted 6855 messages in 213 groups.

http://groups.google.com/groups/profile?enc_user=ul3SQhIYmLD0Oj5Yxp-liP3Vw9uApbyajUBv9M9XLUB2gqkZmQ


And I can't speak for anybody else, but I just assumed it was an April
Fool's question.  I meant to be laughing with the OP, not at him, so
sorry if I misunderstood.

no no you understood prfectly *but* the thing is i am a regular in an
italian language math ng which is haunted by a crackpot who insists that
1/2 * 1/2 cannot be 1/4, "because multiplication means getting bigger",
so i took a semi-serious stance and made a few posts as a statistical
tentative to "convince" said crackpot that the world is not going crazy
(but maybe he is)

thanks

ps: note that my nickname is not unique, and there are a few people
whith the same one... and i didn't ever post using googlegroups


If you think you will persuade a crackpot to drop his lunacy by logical
argument you are clearly an optimist of the first water. But since I
like a challenge (and bearing in mind this is OT so I don't claim to be
an expert) you might try first of all persuading him to agree to the
commutativity of multiplication (i.e. x * y == y * x for any x and y).

If he agrees to that, then get him to agree that x * 1 == x for any x.

If he agrees to that


he does not, since "you cannot multiply something, and not getting some 
more of it" ... he is stuck with the latin etimology of "multiply" 
("multiplicare" means "increase quantity", like in the fish and bread 
miracle)


--
http://mail.python.org/mailman/listinfo/python-list


Re: off topic but please forgive me me and answer

2010-04-03 Thread superpollo

Mensanator ha scritto:

On Apr 3, 8:00 am, superpollo  wrote:

Patrick Maupin ha scritto:






On Apr 2, 2:41 pm, Andreas Waldenburger 
wrote:

While everyone else is mocking you: Can you please elaborate on why you
want to know and what kind of problem you're trying to solve with this?
Also, don't you think you should have picked a maths forum for this
kind of question?

Methinks the OP is fluent in the way of choosing newsgroups.
According to google, he has posted 6855 messages in 213 groups.
http://groups.google.com/groups/profile?enc_user=ul3SQhIYmLD0Oj5Y...
And I can't speak for anybody else, but I just assumed it was an April
Fool's question.  I meant to be laughing with the OP, not at him, so
sorry if I misunderstood.

no no you understood prfectly *but* the thing is i am a regular in an
italian language math ng which is haunted by a crackpot who insists that
1/2 * 1/2 cannot be 1/4, "because multiplication means getting bigger",
so i took a semi-serious stance and made a few posts as a statistical
tentative to "convince" said crackpot that the world is not going crazy
(but maybe he is)


I seriously doubt your crackpot friend actually believes that.
Probably more troll than crackpot. Showing him articles and
programs that prove your premise will accomplish nothing.


probably so, but you cannot imagine the traffic he generates...


However, if you personally wanted information on programming
with rational numbers, you came to the right place.


thanks

ps: note that my nickname is not unique, and there are a few people
whith the same one... and i didn't ever post using googlegroups


What does it mean, "super chicken?


yea!

http://www.renegadechickens.com/chickens/Toons/superchicken.gif
--
http://mail.python.org/mailman/listinfo/python-list


Re: off topic but please forgive me me and answer

2010-04-03 Thread superpollo

Patrick Maupin ha scritto:

On Apr 3, 8:00 am, superpollo  wrote:

sorry if I misunderstood.

no no you understood prfectly *but* the thing is i am a regular in an
italian language math ng which is haunted by a crackpot who insists that
1/2 * 1/2 cannot be 1/4, "because multiplication means getting bigger",
so i took a semi-serious stance and made a few posts as a statistical
tentative to "convince" said crackpot that the world is not going crazy
(but maybe he is)


If I read correctly (using my non-existent Italian, and heavily
relying on my tiny bit of Spanish and a lot of google translate), it
appears that you are what I would call a high-school math/science
teacher, who takes students to competitions?


right -- almost! i don't take them to competitions (i am not an official 
trainer) but sometimes give some general advice to students who would be 
inclined to compete, if they ask me.


bye


--
http://mail.python.org/mailman/listinfo/python-list


Re: off topic but please forgive me me and answer

2010-04-04 Thread superpollo

rantingrick ha scritto:

On Apr 1, 3:44 pm, superpollo  wrote:

how much is one half times one half?


This is amazing, how can such an off topic post based completely on
lunacy exist so long here? 54 posts and counting. I think i had this
very argument in grade school. We have SD'A, Tim Chase, MSRB, and yes
even Steve Holden again participating in the troll fest (even though
some of their arguments are true). Of course i would expect mensenator
to jump into this, but...

A while back i had wondered why Guido never posts to c.l.py anymore.
Was it because he thinks himself better than us, no, it's because of
the "low-brow-infantile-Jerry-Springer-ish-nature" that this list has
imploded into. *puke*


relax mate.

--
http://mail.python.org/mailman/listinfo/python-list


Re: pythonrag

2010-04-05 Thread superpollo

Jason Friedman ha scritto:

I saw this posted in the July issue but did not see any follow-up there:

$ python
Python 2.6.4 (r264:75706, Dec  7 2009, 18:43:55)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.

a = 500
b = 500
a == b

True

a is b

False

p = 50
q = 50
p == q

True

p is q

True


LOL

--
http://mail.python.org/mailman/listinfo/python-list


Re: Recommend Commercial graphing library

2010-04-06 Thread superpollo

Grant Edwards ha scritto:

On 2010-04-06, Grant Edwards  wrote:

On 2010-04-06, Jean-Michel Pichavant  wrote:

Pablo Recio Quijano wrote:
Why must be commercial, when there is open and free alternatives? Like 
GNU Plot.
Gnuplot is ugly. I'm using it because I don't care if it's ugly but it 
clearly lacks of look & feel for presentations, as requested by the OP.

  ^^
  
In other words, Gnuplot presents information in a clear, obfuscated
   
That should be:   unobsuscated


stupid spell-checker...
   
Seriously, most of the graphs I've seen in "presentations" would make

Ed Tufte spin in his grave.


didn't know he died.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python script error when using print

2010-04-06 Thread superpollo

Robbie ha scritto:

Hi all,

So, I'm trying to use Python with an apache2 server to create some web
pages.  The web server is configured and seems to work correctly, but
only with a certain type of script.

For instance, this script works fine

#!/usr/bin/env python
def index():
s = "Hello World"
return s

But, a script like this, does not.
#!/usr/bin/env python
print "hello world"

When I try to use the script with print, the server returns a broken
link error.  There is nothing in the apache error log to help me
understand why it won't work.

Any help?


looks like some cgi issue to me...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Teaching Programming

2010-05-04 Thread superpollo

Samuel Williams ha scritto:

I personally like indentation.

I just wonder whether it is an issue that some people will dislike.


i think there is an issue if you -- say -- produce python code, from 
within another programming environment, to be executed on the fly, at 
least in some instances. there might be problems if for example you 
generate code from a one-line template.


i use a special template system for my job, which goes like this:

...
%%SCHEMA:
...

$A, $B, $C being "loop" control variables reserved to the template 
system. upon parsing, the system generates the corresponding code (say 
"print 12*2**3") and stores the output for further use.


due to design restrictions, i cannot write a code-template which spans 
multiple template-lines, and that is a problem with python, because for 
instance i cannot use conditionals or for loops. if it was C or java 
there wuold be no problem since the source is free-form, so an entire 
program can "live" on a single source line.


bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: Teaching Programming

2010-05-04 Thread superpollo

Stefan Behnel ha scritto:

superpollo, 04.05.2010 12:28:

i think there is an issue if you -- say -- produce python code, from
within another programming environment, to be executed on the fly, at
least in some instances. there might be problems if for example you
generate code from a one-line template.


There are a couple of code generation tools available that you can find 
on PyPI.


However, the main reason why this problem doesn't hurt much in Python is 
that Python is a dynamic language that can get you extremely far without 
generating code. It's simply not necessary in most cases, so people 
don't run into problems with it.


Stefan



Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> A,B=2,3
>>> if A>B:
... print A+B
... else:
... print A**B-B**2
...
-1
>>> A,B=3,2
>>> if A>B:
... print A+B
... else:
... print A**B-B**2
...
5
>>>

tell me please: how can generate the same output (depending on A and B) 
without control structure? i mean in a natural "pythonic" way...


bye

--
http://mail.python.org/mailman/listinfo/python-list


Re: Teaching Programming

2010-05-04 Thread superpollo

Stefan Behnel ha scritto:

superpollo, 04.05.2010 13:23:

Stefan Behnel ha scritto:

the main reason why this problem doesn't hurt much in Python
is that Python is a dynamic language that can get you extremely far
without generating code. It's simply not necessary in most cases, so
people don't run into problems with it.


Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> A,B=2,3
 >>> if A>B:
... print A+B
... else:
... print A**B-B**2
...
-1
 >>> A,B=3,2
 >>> if A>B:
... print A+B
... else:
... print A**B-B**2
...
5

tell me please: how can generate the same output (depending on A and B)
without control structure? i mean in a natural "pythonic" way...


The question is: why do you have to generate the above code in the first 
place? Isn't a function enough that does the above?


of course! *but* if i must generate on-the-fly python code that defines 
a function i am back again to the problem:


def fun():


ecc...

how can i put *that* on a oneliner?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Teaching Programming

2010-05-04 Thread superpollo

Martin P. Hellwig ha scritto:

On 05/04/10 11:28, superpollo wrote:

Samuel Williams ha scritto:

I personally like indentation.

I just wonder whether it is an issue that some people will dislike.



there might be problems if for example you
generate code from a one-line template.


Well a one-line template code generator are great and such, but if the 
output should be human readable it is necessary to have at least some 
form of mark-up control on it. Like newlines and indentations.


or latex markup, in my case...

On the other hand if it is only meant to generate executable code, 
generating an interpreted code might not be the best solution for the 
actual problem.


yes, maybe generating code for a *compiler* might be faster but you must 
consider overhead due to compilation time, especially if code snippets 
are sprinkled by the dozen all over the template file.


For the corner cases (I can think of a couple) it is good to know you 
can use ';' most of the time.




most but not always as i noted (think about loops or function definition)

bye

--
http://mail.python.org/mailman/listinfo/python-list


Re: Teaching Programming

2010-05-04 Thread superpollo

James Mills ha scritto:

On Tue, May 4, 2010 at 9:56 PM, superpollo  wrote:

of course! *but* if i must generate on-the-fly python code that defines a
function i am back again to the problem:


One-liner:

$ python
Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49)
[GCC 4.4.1 (CRUX)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

a, b = 2, 3
print a + b if a > b else a**b - b**2

-1

a, b = 3, 2
print a + b if a > b else a**b - b**2

5

--James


much obliged.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Teaching Programming

2010-05-04 Thread superpollo

Stefan Behnel ha scritto:

superpollo, 04.05.2010 13:56:

Stefan Behnel ha scritto:

The question is: why do you have to generate the above code in the
first place? Isn't a function enough that does the above?


of course! *but* if i must generate on-the-fly python code that defines
a function  [...]


Well, could you provide a use case where you have to generate Python 
code, and where normally written code with some kind of parametrisation 
won't work?


i see your point, and mr mills gave me hints as to how to attack some of 
my problems in such a fashion.


The only thing that currently comes to my mind is a template compiler 
that translates a user provided template into an executable Python 
program. But that should be pretty trivial to do as well. I just 
remembered this little thing on Fredrik's effbot site, which should help 
here:


http://effbot.org/zone/python-code-generator.htm


very good. i will most certainly give it a try.

but i do not think i can use it myself, since my template system wants 
the input to generate the code to stay on a single line ( don't ask :-( )


bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: Teaching Programming

2010-05-04 Thread superpollo

Stefan Behnel ha scritto:

superpollo, 04.05.2010 14:46:

my template system wants
the input to generate the code to stay on a single line ( don't ask :-( )


I hope you don't mind if I still ask. What are you generating and for 
what templating system?


ok, since you asked for it, prepare yourself for a bit of a horror story ;-)

i will answer in my next post

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: Teaching Programming

2010-05-04 Thread superpollo

superpollo ha scritto:

Stefan Behnel ha scritto:

superpollo, 04.05.2010 14:46:

my template system wants
the input to generate the code to stay on a single line ( don't ask 
:-( )


I hope you don't mind if I still ask. What are you generating and for 
what templating system?


ok, since you asked for it, prepare yourself for a bit of a horror story 
;-)


i will answer in my next post


ok here it is.

i am not a programmer or it-guy in the first place; my job is as a high 
school teacher in a field only remotely connected with computers (math 
and physics).


since i have some kind of computer literacy (as opposed to most of my 
colleagues), some years ago i was kindly asked to try and solve a 
"simple" particular problem, that is to write a program that generates 
math exercises (q+a) from an example taken from the textbook. for 
instance, this:


%%TITLE:Sample worksheet
%%
%%SCHEMA:\lim_{x \to }
%%SCHEMA:\frac
%%SCHEMA:{x^3-x^2-x}
%%SCHEMA:{x^3-x^2+x-}\\
%%
%%ANS:FRAC
%%ANSNUM:
%%ANSDEN:
%%
%%AMIN:1
%%AINC:1
%%AMAX:2
%%BMIN:3
%%BINC:1
%%BMAX:4
%%CMIN:2
%%CINC:1
%%CMAX:3

should generate this latex source document:

\documentclass[a4paper,10pt,twocolumn,fleqn]{article}
\title{Sample worksheet}
\pagestyle{empty}
\usepackage[italian]{babel}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{cancel}
\usepackage{mathrsfs}
\usepackage[dvips]{graphicx}
\usepackage{eurosym}
\usepackage{pstricks}
\usepackage{pst-eucl}
\usepackage{pst-poly}
\usepackage{pst-plot}
\frenchspacing
\begin{document}
\section*{\center{\framebox{Sample worksheet}}}
\noindent
\begin{enumerate}
\item
\begin{multline*}
\lim_{x \to 1}
\frac
{x^3+3x^2-4x}
{x^3-x^2+2x-2}\\
\end{multline*}
\item
\begin{multline*}
\lim_{x \to 2}
\frac
{x^3+x^2-6x}
{x^3-2x^2+2x-4}\\
\end{multline*}
\item
\begin{multline*}
\lim_{x \to 2}
\frac
{x^3+2x^2-8x}
{x^3-2x^2+2x-4}\\
\end{multline*}
\item
\begin{multline*}
\lim_{x \to 1}
\frac
{x^3+2x^2-3x}
{x^3-x^2+2x-2}\\
\end{multline*}
\item
\begin{multline*}
\lim_{x \to 1}
\frac
{x^3+2x^2-3x}
{x^3-x^2+3x-3}\\
\end{multline*}
\item
\begin{multline*}
\lim_{x \to 1}
\frac
{x^3+3x^2-4x}
{x^3-x^2+3x-3}\\
\end{multline*}
\item
\begin{multline*}
\lim_{x \to 2}
\frac
{x^3+x^2-6x}
{x^3-2x^2+3x-6}\\
\end{multline*}
\item
\begin{multline*}
\lim_{x \to 2}
\frac
{x^3+2x^2-8x}
{x^3-2x^2+3x-6}\\
\end{multline*}
\end{enumerate}
\subsection*{\center{Answers}}
\begin{enumerate}
\item
\begin{displaymath}
\frac{5}{3}
\end{displaymath}
\item
\begin{displaymath}
\frac{5}{3}
\end{displaymath}
\item
\begin{displaymath}
2
\end{displaymath}
\item
\begin{displaymath}
\frac{4}{3}
\end{displaymath}
\item
\begin{displaymath}
1
\end{displaymath}
\item
\begin{displaymath}
\frac{5}{4}
\end{displaymath}
\item
\begin{displaymath}
\frac{10}{7}
\end{displaymath}
\item
\begin{displaymath}
\frac{12}{7}
\end{displaymath}
\end{enumerate}
\end{document}

which in turn can be used to generate the following pdf file:

http://www.datafilehost.com/download-cc88a19e.html

fine huh? now, for the horror part.

when i began putting down some code i thought that maybe it would take a 
couple of evenings to put up a working prototype, and i was w-r-o-n-g:


1) as i said i am not a professional
2) i decided to use bash shell as a core language for the 
parser/generator ( *sigh* )

3) feautiritis soon crept in

if some of you knows a bit about math and especially algebra, you will 
understand that some of the biggest problems in generating standard math 
notation in to cope with the various layers of traditions and innuendos: 
for example i could generate the string "2x" which is fine; but what 
about "1x" or "-1x" or "0x"? and what about plus signs at the start of 
an expression (normally omitted)? when does a subexpression start? etc 
... there are plenty of icompatible rules and as much as exceptions ...


as you can see i had many problems to solve and i am not trained to cope 
with such issues from a programmatic standpoint.


another thing is that for some features i intended to include i found 
convenient to use python (since it's the language i feel i am more at 
ease with), so i had to cope with template lines like this:


%%SCHEMA:

or even worse:

%%ANSFRCEMBPYC:"~longmapsto~" , $C**2*(3*$A+3*$B+$C) , "~mathrm{(max~loc.)}">\\


to make a long story short: the whole program is now 4775 lines of bash 
code, written by an unqualified amateur under time pressure; sometimes i 
have to hand-modify it to get certain outputs as i expect them to be; 
this in turn breaks other subsystems.


i am ashamed to post the code, and it is a true design nightmare. also 
it is offtopic (being bash).


*but* it was and it is a wonderful experience to learn to program, to 
acknowledge weaknesses end strongnesses of various approaches, to better 
understand the structure of math notation, problem solving end teaching 
techniques.


it is still work in progress though, and i h

Re: Teaching Programming

2010-05-04 Thread superpollo

James Mills ha scritto:

On Tue, May 4, 2010 at 9:56 PM, superpollo  wrote:

of course! *but* if i must generate on-the-fly python code that defines a
function i am back again to the problem:


One-liner:

$ python
Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49)
[GCC 4.4.1 (CRUX)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

a, b = 2, 3
print a + b if a > b else a**b - b**2

-1

a, b = 3, 2
print a + b if a > b else a**b - b**2

5

--James


what if i want an elif clause?

--
http://mail.python.org/mailman/listinfo/python-list


Re: Teaching Programming

2010-05-04 Thread superpollo

superpollo ha scritto:

James Mills ha scritto:

On Tue, May 4, 2010 at 9:56 PM, superpollo  wrote:
of course! *but* if i must generate on-the-fly python code that 
defines a

function i am back again to the problem:


One-liner:

$ python
Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49)
[GCC 4.4.1 (CRUX)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

a, b = 2, 3
print a + b if a > b else a**b - b**2

-1

a, b = 3, 2
print a + b if a > b else a**b - b**2

5

--James


what if i want an elif clause?



my first try obviously falied:

>>> print a + b if a > b elif a=b "WOW" else a**b - b**2
  File "", line 1
print a + b if a > b elif a=b "WOW" else a**b - b**2
^
SyntaxError: invalid syntax

--
http://mail.python.org/mailman/listinfo/python-list


Re: Teaching Programming

2010-05-04 Thread superpollo

superpollo ha scritto:

superpollo ha scritto:

James Mills ha scritto:

On Tue, May 4, 2010 at 9:56 PM, superpollo  wrote:
of course! *but* if i must generate on-the-fly python code that 
defines a

function i am back again to the problem:


One-liner:

$ python
Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49)
[GCC 4.4.1 (CRUX)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

a, b = 2, 3
print a + b if a > b else a**b - b**2

-1

a, b = 3, 2
print a + b if a > b else a**b - b**2

5

--James


what if i want an elif clause?



my first try obviously falied:

 >>> print a + b if a > b elif a=b "WOW" else a**b - b**2
  File "", line 1
print a + b if a > b elif a=b "WOW" else a**b - b**2
^
SyntaxError: invalid syntax



ok i got it:

>>> a,b=2,3
>>> print a + b if a > b else "WOW" if a < b else a**b - b**2
WOW
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Teaching Programming

2010-05-05 Thread superpollo

Martin P. Hellwig ha scritto:

On 05/04/10 12:59, superpollo wrote:

Martin P. Hellwig ha scritto:



For the corner cases (I can think of a couple) it is good to know you
can use ';' most of the time.



most but not always as i noted (think about loops or function definition)


Well through in some exec magic then, for example:
for number in [1,2,3,4]:
def nprint(number):
print(number)
number += 1
nprint(number

translates to:

 >>> exec('for number in [1,2,3,4]:\n\tdef 
nprint(number):\n\t\tprint(number)\n\tnumber += 1\n\tnprint(number)')

2
3
4
5

But if you have an example why indentation is still a problem please 
give it :-)




i think your exec example solved most of my problems. thanks a lot.

bye

--
http://mail.python.org/mailman/listinfo/python-list


Re: Kindly show me a better way to do it

2010-05-08 Thread superpollo

Oltmans ha scritto:

Hi, I've a list that looks like following

a = [ [1,2,3,4], [5,6,7,8] ]

Currently, I'm iterating through it like

for i in [k for k in a]:
for a in i:


i think you used te a identifier for two meanings...


print a

but I was wondering if there is a shorter, more elegant way to do it?



add = lambda a,b: a+b
for i in reduce(add,a):
print i
--
http://mail.python.org/mailman/listinfo/python-list


Re: Kindly show me a better way to do it

2010-05-08 Thread superpollo

superpollo ha scritto:

Oltmans ha scritto:

Hi, I've a list that looks like following

a = [ [1,2,3,4], [5,6,7,8] ]

Currently, I'm iterating through it like

for i in [k for k in a]:
for a in i:


i think you used te a identifier for two meanings...


print a

but I was wondering if there is a shorter, more elegant way to do it?



add = lambda a,b: a+b


or:

from operator import add



for i in reduce(add,a):
print i

--
http://mail.python.org/mailman/listinfo/python-list


Re: Kindly show me a better way to do it

2010-05-08 Thread superpollo

Oltmans ha scritto:

On May 9, 1:53 am, superpollo  wrote:


add = lambda a,b: a+b
for i in reduce(add,a):
 print i


This is very neat. Thank you. Sounds like magic to me. Can you please
explain how does that work? Many thanks again.



here:

http://tinyurl.com/3xp

and here:

http://tinyurl.com/39kdge5

bye
--
http://mail.python.org/mailman/listinfo/python-list


solve a newspaper quiz

2010-05-09 Thread superpollo

"if a b c are digits, solve ab:c=a*c+b"

solved in one minute with no thought:

for a in range(10):
for b in range(10):
for c in range(10):
try:
if (10.*a+b)/c==a*c+b:
print "%i%i:%i=%i*%i+%i" % (a,b,c,a,c,b)
except:
pass

any suggestion for improvement?

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: Extract all words that begin with x

2010-05-10 Thread superpollo

Jimbo ha scritto:

Hello

I am trying to find if there is a string OR list function that will
search a list of strings for all the strings that start with 'a' &
return a new list containing all the strings that started with 'a'.

I have had a search of Python site & I could not find what I am
looking for, does a function like this exist?


>>> sw = lambda s: lambda t: t.startswith(s)
>>> list = ["a string","another one","this is a string","and so is this 
one"]

>>> filter(sw("a"),list)
['a string', 'another one', 'and so is this one']
>>>

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: Extract all words that begin with x

2010-05-10 Thread superpollo

superpollo ha scritto:

Jimbo ha scritto:

Hello

I am trying to find if there is a string OR list function that will
search a list of strings for all the strings that start with 'a' &
return a new list containing all the strings that started with 'a'.

I have had a search of Python site & I could not find what I am
looking for, does a function like this exist?


 >>> sw = lambda s: lambda t: t.startswith(s)
 >>> list = ["a string","another one","this is a string","and so is this 
one"]

 >>> filter(sw("a"),list)
['a string', 'another one', 'and so is this one']
 >>>

bye


of course there is a simpler way:

>>> [string for string in list if string.startswith("a")]
['a string', 'another one', 'and so is this one']
>>>

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: Extract all words that begin with x

2010-05-11 Thread superpollo

Aahz ha scritto:

In article ,
Terry Reedy   wrote:

On 5/10/2010 5:35 AM, James Mills wrote:

On Mon, May 10, 2010 at 6:50 PM, Xavier Ho  wrote:

Have I missed something, or wouldn't this work just as well:


list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
[word for word in list_of_strings if word[0] == 'a']

['awes', 'asdgas']

I would do this for completeness (just in case):


[word for word in list_of_strings if word and word[0] == 'a']

Just guards against empty strings which may or may not be in the list.
 ... word[0:1] does the same thing. All Python programmers should learn 
to use slicing to extract a  char from a string that might be empty.

The method call of .startswith() will be slower, I am sure.


And if it is slower, so what?  Using startswith() makes for faster
reading of the code for me, and I'm sure I'm not the only one.


also, what if the OP intended "words that begin with x" with x a string 
(as opposed to a single character) ?


then startswith is the solution methinks...

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: Slice last char from string without raising exception on empty string (Re: Extract all words that begin with x)

2010-05-11 Thread superpollo

pyt...@bdurham.com ha scritto:

Terry,


 ... word[0:1] does the same thing. All Python programmers should learn to use 
slicing to extract a char from a string that might be empty.


Is there an equivalent way to slice the last char from a string (similar
to an .endswith) that doesn't raise an exception when a string is empty?



could it be:

word[len(word)-1:] ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating over dict and removing some elements

2010-05-11 Thread superpollo

Ulrich Eckhardt ha scritto:

Hi!

I wrote a simple loop like this:

  d = {}
  ...
  for k in d:
  if some_condition(d[k]):
  d.pop(k)

If I run this, Python complains that the dictionary size changed during
iteration. I understand that the iterator relies on the internal structure
not changing, but how would I structure this loop otherwise?


my first thought (untested):

use a copy of d for the if clause, then pop from the original.

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating over dict and removing some elements

2010-05-11 Thread superpollo

superpollo ha scritto:

Ulrich Eckhardt ha scritto:

Hi!

I wrote a simple loop like this:

  d = {}
  ...
  for k in d:
  if some_condition(d[k]):
  d.pop(k)

If I run this, Python complains that the dictionary size changed during
iteration. I understand that the iterator relies on the internal 
structure

not changing, but how would I structure this loop otherwise?


my first thought (untested):

use a copy of d for the if clause, then pop from the original.

bye


i mean:

>>> d = {"name":"max","surname":"zanardi","nick":"zanna"}
>>> dc = copy.copy(d)
>>> dc
{'nick': 'zanna', 'surname': 'zanardi', 'name': 'max'}
>>> for k in dc:
... if dc[k].startswith("z"):
... d.pop(k)
...
'zanna'
'zanardi'
>>> d
{'name': 'max'}
>>> dc
{'nick': 'zanna', 'surname': 'zanardi', 'name': 'max'}
>>>

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: Slice last char from string without raising exception on empty string (Re: Extract all words that begin with x)

2010-05-11 Thread superpollo

James Mills ha scritto:

On Wed, May 12, 2010 at 2:01 AM,   wrote:

word[len(word)-1:]


This works just as well:


word[-1:]


d'uh. ;-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Extract all words that begin with x

2010-05-12 Thread superpollo

Stefan Behnel ha scritto:

superpollo, 11.05.2010 17:03:

Aahz ha scritto:

In article ,
Terry Reedy  wrote:

On 5/10/2010 5:35 AM, James Mills wrote:
On Mon, May 10, 2010 at 6:50 PM, Xavier Ho 
wrote:

Have I missed something, or wouldn't this work just as well:


list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
[word for word in list_of_strings if word[0] == 'a']

['awes', 'asdgas']

I would do this for completeness (just in case):


[word for word in list_of_strings if word and word[0] == 'a']

Just guards against empty strings which may or may not be in the list.

... word[0:1] does the same thing. All Python programmers should
learn to use slicing to extract a char from a string that might be
empty.
The method call of .startswith() will be slower, I am sure.


And if it is slower, so what? Using startswith() makes for faster
reading of the code for me, and I'm sure I'm not the only one.


also, what if the OP intended "words that begin with x" with x a string
(as opposed to a single character) ?


word[:len(x)] == x

will work in that case.


yes ... thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Data store solution need help

2010-05-14 Thread superpollo

Haulyn Jason ha scritto:

Hi, all:

I am a Java programmer, now I am working on a Python program. At the 
moment, I need to store some data from user's input, no database, no 
xml, no txt(we can not make users open the data file by vim or other 
text editor).


security thru obscurity? mmmhhh...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Human word reader

2010-05-15 Thread superpollo

timo verbeek ha scritto:

I'm planning to create a human word program
A human inputs a string
"Give me the weather for London please."
Then I will strip the string.
"weather for london"
Then I get the useful information.
what:"weather" where:"london"
After that I use the info.

I need help with getting the useful information how do I get the place
if I don't now how long the string is?



>>> query = "Give me the weather for London please."
>>> what = query.strip("Give me the ").split()[0]
>>> where = query.strip("Give me the " + what + " for ").split()[0]
>>> print what, where
weather London
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Human word reader

2010-05-15 Thread superpollo

superpollo ha scritto:

timo verbeek ha scritto:

I'm planning to create a human word program
A human inputs a string
"Give me the weather for London please."
Then I will strip the string.
"weather for london"
Then I get the useful information.
what:"weather" where:"london"
After that I use the info.

I need help with getting the useful information how do I get the place
if I don't now how long the string is?



 >>> query = "Give me the weather for London please."
 >>> what = query.strip("Give me the ").split()[0]
 >>> where = query.strip("Give me the " + what + " for ").split()[0]
 >>> print what, where
weather London
 >>>


maybe better not with strip, fot it might not do what i intended (see 
docs); maybe preferable to use "partition" method:


>>> query = "Give me the weather for London please."
>>> what  = query.partition("Give me the ")[2].split()[0]
>>> where = query.partition(" for ")[2].split()[0]
>>> print what, where
weather London
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: parsing XML

2010-05-15 Thread superpollo

kak...@gmail.com ha scritto:

Hi to all, let's say we have the following Xml

  
17.1
6.4
  
  
15.5
7.8
  


How can i get the players name, age and height?
DOM or SAX and how

Thanks
Antonis


another minimal xml.etree.ElementTree solution:

>>> print document

  
17.1
6.4
  
  
15.5
7.8
  

>>> import xml.etree.ElementTree as ET
>>> team = ET.XML(document)
>>> for player in team:
... print player.attrib["name"]
... print player.attrib["age"]
... print player.attrib["height"]
... print
...
Mick Fowler
27
1.96m

Ivan Ivanovic
29
2.04m

>>>

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: parsing XML

2010-05-15 Thread superpollo

superpollo ha scritto:

kak...@gmail.com ha scritto:

Hi to all, let's say we have the following Xml

  
17.1
6.4
  
  
15.5
7.8
  


How can i get the players name, age and height?
DOM or SAX and how

Thanks
Antonis


another minimal xml.etree.ElementTree solution:

 >>> print document

  
17.1
6.4
  
  
15.5
7.8
  

 >>> import xml.etree.ElementTree as ET
 >>> team = ET.XML(document)
 >>> for player in team:
... print player.attrib["name"]
... print player.attrib["age"]
... print player.attrib["height"]
... print
...
Mick Fowler
27
1.96m

Ivan Ivanovic
29
2.04m

 >>>

bye


or, an alternative xml.dom.minidom solution:

>>> import xml.dom.minidom as MD
>>> team = MD.parseString(document)
>>> players = team.getElementsByTagName("player")
>>> for player in players:
... print player.getAttribute("name")
... print player.getAttribute("age")
... print player.getAttribute("height")
... print
...
Mick Fowler
27
1.96m

Ivan Ivanovic
29
2.04m

>>>

bye

--
http://mail.python.org/mailman/listinfo/python-list


Re: Updating values in a dictionary

2010-05-16 Thread superpollo

Thomas ha scritto:

Greetings

I am having a darn awful time trying to update a matrix:

row = dict([(x,0) for x in range(3)])
matrix = dict([(x,row) for x in range(-3,4,1)])

matrix[2][1] += 1
matrix[-1][2] += 1

"""
Got: a 1 in all col 1 and 2
{-3: {0: 0, 1: 1, 2: 1},
 -2: {0: 0, 1: 1, 2: 1},
 -1: {0: 0, 1: 1, 2: 1},
  0: {0: 0, 1: 1, 2: 1},
  1: {0: 0, 1: 1, 2: 1},
  2: {0: 0, 1: 1, 2: 1},
  3: {0: 0, 1: 1, 2: 1}}
Expected: a 1 in row 2 col 1 and row -1 col 2
{-3: {0: 0, 1: 0, 2: 0},
 -2: {0: 0, 1: 0, 2: 0},
 -1: {0: 0, 1: 0, 2: 1},
  0: {0: 0, 1: 0, 2: 0},
  1: {0: 0, 1: 0, 2: 0},
  2: {0: 0, 1: 1, 2: 0},
  3: {0: 0, 1: 0, 2: 0}}
"""

I must be doing something wrong. Researched and researched. Nothing
clicks.


clone the row:

>>> row = dict([(x,0) for x in range(3)])
>>> import copy
>>> matrix = dict([(x,copy.copy(row)) for x in range(-3,4,1)])
>>> matrix[2][1] += 1
>>> matrix[-1][2] += 1
>>> import pprint
>>> pp = pprint.PrettyPrinter()
>>> pp.pprint(matrix)
{-3: {0: 0, 1: 0, 2: 0},
 -2: {0: 0, 1: 0, 2: 0},
 -1: {0: 0, 1: 0, 2: 1},
 0: {0: 0, 1: 0, 2: 0},
 1: {0: 0, 1: 0, 2: 0},
 2: {0: 0, 1: 1, 2: 0},
 3: {0: 0, 1: 0, 2: 0}}
>>>

bye

--
http://mail.python.org/mailman/listinfo/python-list


Re: reading XML file using python

2010-05-17 Thread superpollo

Simon Brunning ha scritto:

On 17 May 2010 09:34:51 UTC+1, shanti bhushan  wrote:

Hi ,
i am new to python.i want to read the XML file using python it ,by
using DOm or SAX any of them.
I want to read the http://www.google.com(any hyper text) from XML and
print that.
please give me the sample program for this.


Your question isn't very clear. Do you want to read the data from a
URL (such as http://www.google.com) and parse it? If so, you probably
don't want an XML parser as such - try Beautiful Soup.


btw, is there any chance that bs will be part of the stdlib anytime soon?

bye
--
http://mail.python.org/mailman/listinfo/python-list


recall function definition from shell

2010-05-18 Thread superpollo

>>> def myfun():
... return "WOW"
...
>>> myfun()
'WOW'
>>>

now, i would like to "list" the funcion definition, something like this:

>>> myfun.somethinglikethis()
def myfun():
return "WOW"
>>>

is there something like this around?

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: recall function definition from shell

2010-05-18 Thread superpollo

Patrick Maupin ha scritto:

On May 18, 12:31 pm, superpollo  wrote:

 >>> def myfun():
... return "WOW"
...
 >>> myfun()
'WOW'
 >>>

now, i would like to "list" the funcion definition, something like this:

 >>> myfun.somethinglikethis()
def myfun():
 return "WOW"
 >>>

is there something like this around?

bye


Sure, just give it a docstring and then you can call help on it:


def myfun():

... ''' myfun returns "WOW" when called.
... This is just a Python __doc__ string
... '''
... return "WOW"
...

help(myfun)


Regards,
Pat


mmm... thanks but not quite what i meant :-(

bye

--
http://mail.python.org/mailman/listinfo/python-list


Re: recall function definition from shell

2010-05-18 Thread superpollo

Patrick Maupin ha scritto:

On May 18, 1:41 pm, superpollo  wrote:

Patrick Maupin ha scritto:




On May 18, 12:31 pm, superpollo  wrote:

 >>> def myfun():
... return "WOW"
...
 >>> myfun()
'WOW'
now, i would like to "list" the funcion definition, something like this:
 >>> myfun.somethinglikethis()
def myfun():
 return "WOW"
is there something like this around?
bye

Sure, just give it a docstring and then you can call help on it:

def myfun():

... ''' myfun returns "WOW" when called.
... This is just a Python __doc__ string
... '''
... return "WOW"
...

help(myfun)

Regards,
Pat

mmm... thanks but not quite what i meant :-(

bye


Well, I don't think Python remembers exactly how you typed it in


yes python does not, but maybe the *shell* does, or so i thought. i just 
wanted to dump the code for the function in a file, after i tested in 
the shell...



--
http://mail.python.org/mailman/listinfo/python-list


Re: recall function definition from shell

2010-05-18 Thread superpollo

Peter Otten ha scritto:

superpollo wrote:


Patrick Maupin ha scritto:

On May 18, 1:41 pm, superpollo  wrote:

Patrick Maupin ha scritto:




On May 18, 12:31 pm, superpollo  wrote:

 >>> def myfun():
... return "WOW"
...
 >>> myfun()
'WOW'
now, i would like to "list" the funcion definition, something like
this:
 >>> myfun.somethinglikethis()
def myfun():
 return "WOW"
is there something like this around?
bye

Sure, just give it a docstring and then you can call help on it:

def myfun():

... ''' myfun returns "WOW" when called.
... This is just a Python __doc__ string
... '''
... return "WOW"
...

help(myfun)

Regards,
Pat

mmm... thanks but not quite what i meant :-(

bye

Well, I don't think Python remembers exactly how you typed it in

yes python does not, but maybe the *shell* does, or so i thought. i just
wanted to dump the code for the function in a file, after i tested in
the shell...


You could try ipython:

$ ipython
Python 2.6.4 (r264:75706, Dec  7 2009, 18:43:55)
Type "copyright", "credits" or "license" for more information.

IPython 0.10 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help  -> Python's own help system.
object?   -> Details about 'object'. ?object also works, ?? prints more.

In [1]: def f():
   ...: return 42
   ...:

In [2]: f()
Out[2]: 42

In [3]: %save tmp.py 1
The following commands were written to file `tmp.py`:
def f():
return 42


In [4]:
Do you really want to exit ([y]/n)?
$ cat tmp.py
def f():
return 42
$

Peter




hey great! thanks a lot!

best regards

--
http://mail.python.org/mailman/listinfo/python-list


Re: remove elements incrementally from a list

2010-05-19 Thread superpollo

Javier Montoya ha scritto:

Dear all,

I've a list of float numbers and I would like to delete incrementally
a set of elements in a given range of indexes, sth. like:

for j in range(beginIndex, endIndex+1):
   print ("remove [%d] => val: %g" % (j, myList[j]))
   del myList[j]

However, since I'm iterating over the same list, the indexes (range)
are not valid any more for the new list.
Does anybody has some suggestions on how to delete the elements
properly?


clone the list, and then loop over the copy while deleting from the original

bye
--
http://mail.python.org/mailman/listinfo/python-list


ipython question

2010-05-19 Thread superpollo

In [39]: def f():
   : return 42
   :

In [40]: %psource f
No source found for f

In [41]:

i expected to see the source...
--
http://mail.python.org/mailman/listinfo/python-list


function that counts...

2010-05-19 Thread superpollo

... how many positive integers less than n have digits that sum up to m:

In [197]: def prttn(m, n):
tot = 0
for i in range(n):
s = str(i)
sum = 0
for j in range(len(s)):
sum += int(s[j])
if sum == m:
tot += 1
return tot
   .:

In [207]: prttn(25, 1)
Out[207]: 348

any suggestion for pythonizin' it?

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: ipython question

2010-05-19 Thread superpollo

Robert Kern ha scritto:

On 5/19/10 12:11 PM, superpollo wrote:

In [39]: def f():
: return 42
:

In [40]: %psource f
No source found for f

In [41]:

i expected to see the source...


You will want to ask IPython questions on the IPython mailing list:

  http://mail.scipy.org/mailman/listinfo/ipython-user

The reason you do not get the source is because there is no file that 
contains functions defined in the interactive interpreter. %psource uses 
the inspect module, and the inspect module explicitly only looks in real 
files


but still:

In [218]: def f():
   .: return 42
   .:

In [219]: %save tmp.py 218
File `tmp.py` exists. Overwrite (y/[N])? y
The following commands were written to file `tmp.py`:
def f():
return 42


In [220]: !cat tmp.py
def f():
return 42

In [221]: %psource f
No source found for f
--
http://mail.python.org/mailman/listinfo/python-list


Re: ipython question

2010-05-19 Thread superpollo

superpollo ha scritto:

Robert Kern ha scritto:

On 5/19/10 12:11 PM, superpollo wrote:

In [39]: def f():
: return 42
:

In [40]: %psource f
No source found for f

In [41]:

i expected to see the source...


You will want to ask IPython questions on the IPython mailing list:

  http://mail.scipy.org/mailman/listinfo/ipython-user

The reason you do not get the source is because there is no file that 
contains functions defined in the interactive interpreter. %psource 
uses the inspect module, and the inspect module explicitly only looks 
in real files


but still:

In [218]: def f():
   .: return 42
   .:

In [219]: %save tmp.py 218
File `tmp.py` exists. Overwrite (y/[N])? y
The following commands were written to file `tmp.py`:
def f():
return 42


In [220]: !cat tmp.py
def f():
return 42

In [221]: %psource f
No source found for f


maybe i got it:

In [230]: import tmp

In [231]: %psource tmp.f
def f():
return 42


--
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-19 Thread superpollo

Jerry Hill ha scritto:

On Wed, May 19, 2010 at 3:58 PM, superpollo  wrote:

... how many positive integers less than n have digits that sum up to m:

...

any suggestion for pythonizin' it?


This is how I would do it:

def prttn(m, n):
"""How many positive integers less than n have digits that sum up to m"""
total = 0
for testval in range(n):
sumofdigits = sum(int(char) for char in str(testval))


this line gives me this:

TypeError: 'int' object is not callable

is it some new feature in >2.5 ?


if sumofdigits == m:
total += 1
return total

I added a docstring to the function, saying what it does, and what the
arguments are supposed to represent.  I also moved the
convert-to-string-and-sum-the-digits logic into a single generator
expression that's passed to the builtin sum function.  Oh, and I tried
to use slightly more expressive variable names.


--
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-19 Thread superpollo

René 'Necoro' Neumann ha scritto:

Am 19.05.2010 21:58, schrieb superpollo:

... how many positive integers less than n have digits that sum up to m:

In [197]: def prttn(m, n):
tot = 0
for i in range(n):
s = str(i)
sum = 0
for j in range(len(s)):
sum += int(s[j])
if sum == m:
tot += 1
return tot
   .:

In [207]: prttn(25, 1)
Out[207]: 348

any suggestion for pythonizin' it?

bye


An idea would be:


def prttn(m, n):

... return sum(1 for x in range(n) if sum(map(int, str(x))) == m)


TypeError: 'int' object is not callable

on 2.5.4



A small oneliner :)

(I first had "return len([x for x in ...])" but the above avoids
creating an intermediate list)

- René


--
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-19 Thread superpollo

Jerry Hill ha scritto:

On Wed, May 19, 2010 at 4:25 PM, superpollo  wrote:

Jerry Hill ha scritto:

   sumofdigits = sum(int(char) for char in str(testval))

this line gives me this:

TypeError: 'int' object is not callable

is it some new feature in >2.5 ?


No, sum() has been a builtin since Python 2.3.  Based on your first
post, you have probably shadowed the builtin "sum" function by
assigning an integer to a variable named "sum".


o my... thanks!

In [266]: del(sum)

In [267]: def prttn2(m, n):
"""How many positive integers less than n have digits that sum up 
to m"""

total = 0
for testval in range(n):
sumofdigits = sum(int(char) for char in str(testval))
if sumofdigits == m:
total += 1
return total
   .:

In [275]: def prttn3(m, n):
return sum(1 for x in range(n) if sum(map(int, str(x))) == m)
   .:

In [277]: prttn(25, 1)
Out[277]: 348

In [278]: prttn2(25, 1)
Out[278]: 348

In [279]: prttn3(25, 1)
Out[279]: 348

ok, bye!
--
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-19 Thread superpollo

Mark Dickinson ha scritto:

On May 19, 9:30 pm, superpollo  wrote:

René 'Necoro' Neumann ha scritto:

An idea would be:

def prttn(m, n):

...return sum(1 for x in range(n) if sum(map(int, str(x))) == m)

TypeError: 'int' object is not callable

on 2.5.4


The TypeError is almost certainly because you've created a integer
'sum' variable in your script/interpreter session, hiding the built-in
sum function.


thx
--
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-20 Thread superpollo

Steven D'Aprano ha scritto:

On Wed, 19 May 2010 22:58:22 +0200, superpollo wrote:


In [266]: del(sum)



del is a statement, not a function, so the brackets are pointless. This 
is like writing:


x = (1)

instead of

x = 1

`del sum` is all you need.


sorry about that, thanks a lot!

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-20 Thread superpollo

Steven D'Aprano ha scritto:

On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote:


... how many positive integers less than n have digits that sum up to m:

In [197]: def prttn(m, n):


Does the name "prttn" mean anything? I'm afraid I keep reading it as a 
mispelling of "print n".


pArtItIOn




[...]

 s = str(i)
 sum = 0
 for j in range(len(s)):
 sum += int(s[j])


Rather than iterating over an index j = 0, 1, 2, ... and then fetching 
the jth character of the string, you can iterate over the characters 
directly. So the inner loop is better written:


for c in s:
sum += int(c)


d'oh! some day i will learn to speak pythonese!

thanks

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-20 Thread superpollo

Richard Thomas ha scritto:

For this kind of problem you should avoid all that stringification. I
find it best to deal with sequences of digits of a fixed length and go
from there. For example:

def count1(m, n, cache={}):
"""Number of digit sequences of length `n` summing to `m`."""
if n < 0 or m < 0:
return 0
elif n == 0:
return int(m == 0)
elif (m, n) in cache:
return cache[m, n]
# This is an optimisation using the combinatoric choose function.
#elif m < 10:
#result = choose(n + m - 1, n - 1)
else:
result = 0
for digit in xrange(min(10, m + 1)):
result += count1(m - digit, n - 1)
cache[m, n] = result
return result

Notice the caching of results. With this we can compute the required
thing quite easily:

def count2(m, n):
"""Number of numbers less than `n` whose digits sum to `m`."""
result = 0
digits = map(int, str(n))
length = len(digits)
for idx, digit in enumerate(digits):
for seq_digit in xrange(digit):
seq_limit = m - seq_digit
seq_length = length - idx - 1
result += count1(seq_limit, seq_length)
m -= digit
return result

Essentially we move through the number left to right, choose digits
less than the digit in the number and count digit sequences to fill
the remainder. Then fix the actual digit and step forward.

An approach like this avoids the relatively slow stringification
process and makes decent use of caching and iteration (both easy and
efficient in Python).

In [1]: count2(25, 1)
Out[1]: 348

In [2]: timeit count2(25, 1)
10 loops, best of 3: 12.6 us per loop


wow.

impressive, thanks.

--
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-20 Thread superpollo

Peter Pearson ha scritto:

On Wed, 19 May 2010 21:58:04 +0200, superpollo  wrote:

... how many positive integers less than n have digits that sum up to m:


If it's important for the function to execute quickly for large n,
you might get a useful speedup by testing only every ninth integer,
since any two integers whose digits add up to m differ by a multiple
of 9.  A simple application of this observation would be to test
range( m % 9, n, 9 ) rather than testing range( 1, n ).

I suspect that further applications of number theory would
provide additional, substantial speedups, but this wanders
away from the subject of Python.



great suggestion, thanks!

--
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-20 Thread superpollo

Grant Edwards ha scritto:

On 2010-05-20, superpollo  wrote:

Steven D'Aprano ha scritto:

On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote:


... how many positive integers less than n have digits that sum up to m:

In [197]: def prttn(m, n):
Does the name "prttn" mean anything? I'm afraid I keep reading it as a 
mispelling of "print n".

pArtItIOn


One might be tempted to suggest the name "partition".


no kidding: i was afraid to use some reserved word...
--
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-24 Thread superpollo

Jean-Michel Pichavant ha scritto:

Jerry Hill wrote:

On Wed, May 19, 2010 at 3:58 PM, superpollo  wrote:
 

... how many positive integers less than n have digits that sum up to m:


...
 

any suggestion for pythonizin' it?



This is how I would do it:

def prttn(m, n):
"""How many positive integers less than n have digits that sum up 
to m"""

total = 0
for testval in range(n):
sumofdigits = sum(int(char) for char in str(testval))
if sumofdigits == m:
total += 1
return total

I added a docstring to the function, saying what it does, and what the
arguments are supposed to represent.  I also moved the
convert-to-string-and-sum-the-digits logic into a single generator
expression that's passed to the builtin sum function.  Oh, and I tried
to use slightly more expressive variable names.

  

my favorite solutio nso far.

@ OP

What means prttn ? 


i already answered this downthreads...

something ... I don't find the word, something like un-intuitive. Sounds 
like homework.


it is not.
--
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-25 Thread superpollo

Jean-Michel Pichavant ha scritto:

superpollo wrote:

Jean-Michel Pichavant ha scritto:

Jerry Hill wrote:

On Wed, May 19, 2010 at 3:58 PM, superpollo  wrote:
 
... how many positive integers less than n have digits that sum up 
to m:


...
 

any suggestion for pythonizin' it?



This is how I would do it:

def prttn(m, n):
"""How many positive integers less than n have digits that sum 
up to m"""

total = 0
for testval in range(n):
sumofdigits = sum(int(char) for char in str(testval))
if sumofdigits == m:
total += 1
return total

I added a docstring to the function, saying what it does, and what the
arguments are supposed to represent.  I also moved the
convert-to-string-and-sum-the-digits logic into a single generator
expression that's passed to the builtin sum function.  Oh, and I tried
to use slightly more expressive variable names.

  

my favorite solutio nso far.

@ OP

What means prttn ? 


i already answered this downthreads...

something ... I don't find the word, something like un-intuitive. 
Sounds like homework.


it is not.

My apologies then, for both statements.
I still don't see "how many positive integers less than n have digits 
that sum up to m" makes it a "partition" though if that what prttn 
means. Surely because I miss the context.


JM


ok, this is the mistery. it was inspired by a question on e.c.m.:

http://groups.google.it/group/es.ciencia.matematicas/msg/f8f09672bd8a052a

the first question is (somewhat) an instance of:

http://en.wikipedia.org/wiki/Partition_(number_theory)

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a single list

2010-05-29 Thread superpollo

Astley Le Jasper ha scritto:

This is probably a really silly question but, given the example code
at the bottom, how would I get a single list?

What I currently get is:

('id', 20, 'integer')
('companyname', 50, 'text')
[('focus', 30, 'text'), ('fiesta', 30, 'text'), ('mondeo', 30,
'text'), ('puma', 30, 'text')]
('contact', 50, 'text')
('email', 50, 'text')

what I would like is:

('id', 20, 'integer')
('companyname', 50, 'text')
('focus', 30, 'text'),
('fiesta', 30, 'text'),
('mondeo', 30, 'text'),
('puma', 30, 'text'),
('contact', 50, 'text')
('email', 50, 'text')

SAMPLE CODE>>>
def getproducts():
temp_list=[]
product_list=['focus','fiesta','mondeo','puma'] #usually this
would come from a db
for p in product_list:
temp_list.append((p,30,'text'))
return temp_list

def createlist():
column_title_list = (
("id",20,"integer"),
("companyname",50,"text"),
getproducts(),
("contact",50,"text"),
("email",50,"text"),
)
return column_title_list

for item in createlist():
print item


>>> def createlist():
... column_title_list = [
... ("id",20,"integer"),
... ("companyname",50,"text")]
... column_title_list += getproducts()
... column_title_list += [
... ("contact",50,"text"),
... ("email",50,"text")]
... return column_title_list
...
>>> for item in createlist():
... print item
...
('id', 20, 'integer')
('companyname', 50, 'text')
('focus', 30, 'text')
('fiesta', 30, 'text')
('mondeo', 30, 'text')
('puma', 30, 'text')
('contact', 50, 'text')
('email', 50, 'text')
>>>

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reading file bit by bit

2010-06-07 Thread superpollo

Ulrich Eckhardt ha scritto:

Peter Otten wrote:

Ulrich Eckhardt wrote:

Says Python:


bin(192)

'0x1100'

Hmm, if that's what /your/ Python says, here's mine to counter:


bin(192)

'0_totally_faked_binary_0011'


Argh! Of course one of my Pythons says '0b1100' and not what I mistyped
above =(


mine goes like this:

>>> bin(192)
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'bin' is not defined

--
http://mail.python.org/mailman/listinfo/python-list


Re: GUIs - A Modest Proposal

2010-06-11 Thread superpollo

Andreas Waldenburger ha scritto:

On Thu, 10 Jun 2010 23:00:37 -0700 (PDT) rantingrick
 wrote:


On Jun 11, 12:17 am, ant  wrote:

I like the points about backwards compatibility. Presumably that
reason alone is enough to keep Tkinter in the standard library for a
long while.

I don't see why that is a good reason. Download Tkinter and your
backward compatible again. The majority don't use it anyway. I would
bet that only myself, Kevin, and only a handful of others use Tkinter
for anything more than education purposes.


I have a strong suspicion that Tkinter may be used a lot more than is
made public (isn't anything?). I'm especially thinking about scientists
who write special purpose data processing or control programs with
basic GUIs. These things don't have to be pretty or anything and it is
a HUGE advantage if you don't have to jump through any hoops to get it
to run on different platforms.

/W



e.g.:

http://heim.ifi.uio.no/~hpl/INF5660/PyBasics.pdf

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: a +b ?

2010-06-11 Thread superpollo

yanhua ha scritto:

hi,all??
it's a simple question:
input two integers A and B in a line,output A+B?

this is my program:
s = input()


this does not work


t = s.split()
a = int(t[0])
b = int(t[1])
print(a+b)

but i think it's too complex,can anybody tell to slove it with less code.


>>> import operator
>>> print reduce(operator.add, map(int, raw_input().split()))
124312 41242
165554
>>>

bye

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a +b ?

2010-06-11 Thread superpollo

Simon Brunning ha scritto:

2010/6/11 yanhua :

hi,all!
it's a simple question:
input two integers A and B in a line,output A+B?


print sum(int(i) for i in raw_input("Please enter some integers: ").split())


LOL
--
http://mail.python.org/mailman/listinfo/python-list


pythonize this!

2010-06-15 Thread superpollo
goal (from e.c.m.): evaluate 
1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three 
consecutive + must be followed by two - (^ meaning ** in this context)


my solution:

>>> s = 0
>>> for i in range(1, 2011):
... s += i**2
... if not (i+1)%5:
... s -= 2*i**2
... if not i%5:
... s -= 2*i**2
...
>>> print s
536926141
>>>

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: pythonize this!

2010-06-15 Thread superpollo

Ulrich Eckhardt ha scritto:

superpollo wrote:

... s += i**2
... if not (i+1)%5:
... s -= 2*i**2
... if not i%5:
... s -= 2*i**2


if not (i % 5) in [1, 2]:
s += i**2
else:
s -= i**2

Untested code.


does not work:

>>> s = 0
>>> for i in range(1, 2011):
... if not (i % 5) in [1, 2]:
... s += i**2
... else:
... s -= i**2
...
>>> print s
546627205
>>>

but this does:

>>> s = 0
>>> for i in range(1, 2011):
... if i % 5 in [1, 2, 3]:
... s += i**2
... else:
... s -= i**2
...
>>> print s
536926141

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: pythonize this!

2010-06-15 Thread superpollo

Peter Otten ha scritto:

superpollo wrote:


goal (from e.c.m.): evaluate
1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three
consecutive + must be followed by two - (^ meaning ** in this context)



from itertools import cycle, izip
sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011)))

536926141


don't understand it bit i like this a lot!
--
http://mail.python.org/mailman/listinfo/python-list


Re: pythonize this!

2010-06-15 Thread superpollo

superpollo ha scritto:

Peter Otten ha scritto:

superpollo wrote:


goal (from e.c.m.): evaluate
1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three
consecutive + must be followed by two - (^ meaning ** in this context)



from itertools import cycle, izip
sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011)))

536926141


don't understand it bit i like this a lot!

  ^^^

*but*
--
http://mail.python.org/mailman/listinfo/python-list


Re: GUIs - A Modest Proposal

2010-06-15 Thread superpollo

lkcl ha scritto:
...

That sounds too good to be true.


 yup, it does.  how can one person, a free software developer, have
come up with something like "The Holy Grail" of software development,
right?  when all the money in the world, from ibm, adobe, microsoft,
google, nokia and so on _hasn't_ managed it, in what... 20 years of
computer science, right?  i must be some sort of egomaniac, attention-
seeker, snake-oil-seller or just an outright liar, right?  those _are_
supposed to be rhetorical questions :)


I sort of have to be reading too much
into what you're saying.


 no, you got it.  does what it says on the tin.


mind you, i am no python expert, but i really look forward to seeing 
pyjamas in the stdlib :-) anytime soon?


bye

--
http://mail.python.org/mailman/listinfo/python-list


Re: pythonize this!

2010-06-15 Thread superpollo

Stefan Behnel ha scritto:

superpollo, 15.06.2010 14:55:

Peter Otten ha scritto:

superpollo wrote:


goal (from e.c.m.): evaluate
1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three
consecutive + must be followed by two - (^ meaning ** in this context)



from itertools import cycle, izip
sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 
2011)))

536926141


don't understand it bit i like this a lot!


Didn't you want to get it "pythonized"? If it's not understandable, it 
can't be pythonic.


maybe i must study itertools then ;-)

thanks

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: pythonize this!

2010-06-15 Thread superpollo

Paul Rubin ha scritto:

superpollo  writes:

goal (from e.c.m.): evaluate
1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three
consecutive + must be followed by two - (^ meaning ** in this context)


print sum([-1,1,1,1,-1][i%5]*i**2 for i in xrange(1,2011))


beautiful.

thx
--
http://mail.python.org/mailman/listinfo/python-list


python source code -> win/dos executable (on linux)

2010-06-25 Thread superpollo

hi.

suppose i work in a linux environment, but i would like to ship a 
win/dos executable file from time to time, just for test purposes (my 
"testers" are windows users and don't want to go through the hassle of 
installing python on their win boxes). what is the best way to do that? 
(the application should be a simple console app, but my question applies 
to gui/tkinter apps too)


hint: when i do the same in C, i usually do something like:

http://www.youtube.com/watch?v=rhe6N7FB1D4

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: python source code -> win/dos executable (on linux)

2010-06-28 Thread superpollo

Lawrence D'Oliveiro ha scritto:
In message <4c24c152$0$31381$4fafb...@reader1.news.tin.it>, superpollo 
wrote:



suppose i work in a linux environment, but i would like to ship a
win/dos executable file from time to time, just for test purposes (my
"testers" are windows users and don't want to go through the hassle of
installing python on their win boxes).


Is it really such a hassle to install things on Windows?


no, but it *IS* to explain it to dumb users... :-(

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: automate minesweeper with python

2010-07-02 Thread superpollo

Ethan Furman ha scritto:

Terry Reedy wrote:

On 7/1/2010 6:42 PM, Emile van Sebille wrote:


On 7/1/2010 2:52 PM Jay said...


pywinauto looks to be almost perfect. All I need now is to read the
numbers uncovered when a minesweeper square is clicked on, or that I
just hit a mine.



... or, you could always win...

http://www.daniweb.com/forums/thread186209.html



Did you actually try it? Though skeptical, I did, briefly, until I 
decided that it probably should have been dated April 1. There is no 
way to enter text into minesweeper, nor to make it full screen, nor, 
as far as I know, for it to toggle pixels outside its window.


The pixel can be hard to see depending on your background colors and 
whether your screen is adjusted correctly (I could see the white, but 
not the black).  But on XP Pro is still works.


works for me too

bye
--
http://mail.python.org/mailman/listinfo/python-list


timer

2009-06-29 Thread superpollo

hi folks.

the follwing shoud print 'stuff' for 3 seconds and then stop. why it 
does not work? (prints stuff forever)


  1 #!/usr/bin/python
  2
  3 import threading
  4 import sys
  5
  6 t = threading.Timer(3.0, sys.exit)
  7 t.start()
  8 while True:
  9 print "stuff ",

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: timer

2009-06-30 Thread superpollo

Paul Moore wrote:

2009/6/29 MRAB :


superpollo wrote:


hi folks.

the follwing shoud print 'stuff' for 3 seconds and then stop. why it does
not work? (prints stuff forever)

1 #!/usr/bin/python
2
3 import threading
4 import sys
5
6 t = threading.Timer(3.0, sys.exit)
7 t.start()
8 while True:
9 print "stuff ",



The Timer runs the function in another thread. Perhaps sys.exit is just
exiting that thread and not the main thread.



sys.exit raises a SystemExit exception, which will get handled in the
new thread (where it won't do anything). Conceded, this isn't
particularly intuitive.

For a non-toy example, you'd probably create an Event object, use your
timer to set the event, and your while loop would do while
event.is_set(), so the problem wouldn't arise.


thank u paul. if u dont mind, would you give me a more detailed piece of 
code that does what i mean?


tia
--
http://mail.python.org/mailman/listinfo/python-list


Re: timer

2009-06-30 Thread superpollo

Paul Moore wrote:

2009/6/29 MRAB :


superpollo wrote:


hi folks.

the follwing shoud print 'stuff' for 3 seconds and then stop. why it does
not work? (prints stuff forever)

1 #!/usr/bin/python
2
3 import threading
4 import sys
5
6 t = threading.Timer(3.0, sys.exit)
7 t.start()
8 while True:
9 print "stuff ",



The Timer runs the function in another thread. Perhaps sys.exit is just
exiting that thread and not the main thread.



sys.exit raises a SystemExit exception, which will get handled in the
new thread (where it won't do anything). Conceded, this isn't
particularly intuitive.

For a non-toy example, you'd probably create an Event object, use your
timer to set the event, and your while loop would do while
event.is_set(), so the problem wouldn't arise.

Paul.


so why this does not work?

  1 #!/usr/bin/python
  2
  3 import threading
  4
  5 e = threading.Event()
  6 t = threading.Timer(3.0, e.set())
  7 t.start()
  8 while not e.isSet():
  9 print "stuff ",

it does *NOT* print (but it should, shouldn't it?), then exits after 3 
sec but with error:


Exception in thread Thread-1:Traceback (most recent call last):
  File "/usr/lib/python2.3/threading.py", line 442, in __bootstrap
self.run()
  File "/usr/lib/python2.3/threading.py", line 575, in run
self.function(*self.args, **self.kwargs)
TypeError: 'NoneType' object is not callable

what gives?
--
http://mail.python.org/mailman/listinfo/python-list


Re: timer

2009-06-30 Thread superpollo

Paul Moore wrote:

2009/6/30 superpollo :


Paul Moore wrote:


For a non-toy example, you'd probably create an Event object, use your
timer to set the event, and your while loop would do while
event.is_set(), so the problem wouldn't arise.


thank u paul. if u dont mind, would you give me a more detailed piece of
code that does what i mean?



No problem:

import threading

e = threading.Event()
t = threading.Timer(3.0, e.set)
t.start()

while not e.is_set():
print "Hello, threading world"

Hope this helps,
Paul


hi

while i was waiting 4 ur reply, i posted an almost equal example, but it 
does not work...

--
http://mail.python.org/mailman/listinfo/python-list


Re: timer

2009-06-30 Thread superpollo

Paul Moore wrote:

2009/6/30 superpollo :


Paul Moore wrote:


For a non-toy example, you'd probably create an Event object, use your
timer to set the event, and your while loop would do while
event.is_set(), so the problem wouldn't arise.


thank u paul. if u dont mind, would you give me a more detailed piece of
code that does what i mean?



No problem:

import threading

e = threading.Event()
t = threading.Timer(3.0, e.set)
t.start()

while not e.is_set():
print "Hello, threading world"

Hope this helps,
Paul


do not bother answering... my fault.

i wrote e.set() and not e.set



thanks again
--
http://mail.python.org/mailman/listinfo/python-list


Re: timer

2009-06-30 Thread superpollo
i would like to thank each and everyone for help given, and aplologise 
for my inaccuracy.


thanks 10**3!

superchicken
--
http://mail.python.org/mailman/listinfo/python-list


stringio+tarfile

2009-07-02 Thread superpollo

why the following does not work? can you help me correct (if possible)?

  1 import tarfile
  2 import StringIO
  3 sf1 = StringIO.StringIO("one\n")
  4 sf2 = StringIO.StringIO("two\n")
  5 tf = StringIO.StringIO()
  6 tar = tarfile.open(tf , "w")
  7 for name in [sf1 , sf2]:
  8 tar.add(name)
  9 print tf
 10 sf1.close()
 11 sf2.close()
 12 tf.close()
 13 tar.close()

tia
--
http://mail.python.org/mailman/listinfo/python-list


Re: stringio+tarfile

2009-07-03 Thread superpollo
First problem I see is all those numbers before the lines.  That's not 
valid python.


Assuming that was a transcription error


not so. i intentionally add linenumbers to facilitare reference to the 
code, but if it is a nuisance i will not include them anymore.


thanks
--
http://mail.python.org/mailman/listinfo/python-list


Re: stringio+tarfile

2009-07-03 Thread superpollo
thanks to the guys who bothered to answer me even using their chrystal 
ball ;-)


i'll try to be more specific.

yes: i want to create a tar file in memory, and add some content from a
memory buffer...

my platform:

$ uname -a
Linux fisso 2.4.24 #1 Thu Feb 12 19:49:02 CET 2004 i686 GNU/Linux
$ python -V
Python 2.3.4

following some suggestions i modified the code:

$ cat tar001.py
import tarfile
import StringIO
sfo1 = StringIO.StringIO("one\n")
sfo2 = StringIO.StringIO("two\n")
tfo = StringIO.StringIO()
tar = tarfile.open(fileobj=tfo , mode="w")
ti = tar.gettarinfo(fileobj=tfo)
for sfo in [sfo1 , sfo2]:
tar.addfile(fileobj=sfo , tarinfo=ti)
print tfo

and that's what i get:

$ python tar001.py > tar001.out
Traceback (most recent call last):
  File "tar001.py", line 7, in ?
ti = tar.gettarinfo(fileobj=tfo)
  File "/usr/lib/python2.3/tarfile.py", line 1060, in gettarinfo
name = fileobj.name
AttributeError: StringIO instance has no attribute 'name'

can you help?

TIA

ps: i'd also like that the tar file has names for the buffers, so than 
once output the file can be untarred with /bin/tar into regular files...

--
http://mail.python.org/mailman/listinfo/python-list


Re: stringio+tarfile

2009-07-03 Thread superpollo

Peter Otten wrote:


gettarinfo() expects a real file, not a file-like object.
You have to create your TarInfo manually.


ok... which attributes are mandatory, and which optional?



I recommend that you have a look into the tarfile module's source code.



i will try... but:


$ cat /usr/lib/python2.3/tarfile.py | wc -l
1938

wow! it'll take some time ;-)



The following seems to work:

import sys
import time
import tarfile
import StringIO

sf1 = "first.txt", StringIO.StringIO("one one\n")
sf2 = "second.txt", StringIO.StringIO("two\n")
tf = StringIO.StringIO()

tar = tarfile.open(fileobj=tf , mode="w")

mtime = time.time()
for name, f in [sf1 , sf2]:
ti = tarfile.TarInfo(name)
ti.size = f.len
ti.mtime = mtime
# add more attributes as needed 
tar.addfile(ti, f)


sys.stdout.write(tf.getvalue())

Peter



much obliged mr otten

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: stringio+tarfile (or better... zipfile)

2009-07-03 Thread superpollo
following the excellent suggestions received, i tried to adapt the 
problem to zipfile, and i wrote this:


$ cat zip001.py
import sys
import zipfile
import StringIO

nb1 = "first.txt", StringIO.StringIO("one one\n")
nb2 = "second.txt", StringIO.StringIO("two\n")
zb = StringIO.StringIO()

zip = zipfile.ZipFile(zb , "w" , zipfile.ZIP_DEFLATED)

for name , buffer in [nb1 , nb2]:
zip.writestr(name, buffer.getvalue()*1000)
zip.close()

sys.stdout.write(zb.getvalue())
$ python zip001.py > zip001.out
$ unzip -l zip001.out
Archive:  zip001.out
  Length Date   TimeName
    
 8000  07-03-09 22:07   first.txt
 4000  07-03-09 22:07   second.txt
    ---
12000   2 files
$

it seems to me thaz zipfile has a simpler usability... any comments?

thanks again and bye bye
--
http://mail.python.org/mailman/listinfo/python-list


older pythons

2009-07-09 Thread superpollo

hi everybody.

i have a certain set of old python scripts and data used by said scripts 
which were written using python 2.3


in particular i used some features which were later modified or 
deprecated by the language newer versions (e.g.: cmp(), print as 
keyword, and such...)


for reasons i find hard to explain briefly, it is unfeasible at the 
moment to modify scripts and data to adapt to the changes


now: i ask if it is possible to have different versions of python 
installed on my system (linux debian) so that i can continue to use 
python 2.3 (as "python" from the shell) but i can also use - say - 
python 3.1 (maybe as "python3.1" from the shell)


if yes: is there a known recommended way to do so?

thanks a lot

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: older pythons

2009-07-09 Thread superpollo

Adrian Dziubek wrote:

The recommended Debian way is update-alternatives. I find it a bit
unintuitive, so I have to read through the documentation every time I
use it, but it should be able link a chosen version of python to /usr/
bin/python. I don't know if it's set up by default, I have only one
version installed.
--
Adrian


what i was asking for is about a way to *INSTALL* and mantain different 
python versions, a task i think is not unusal for developers.


thanks anyway for reply

bye
--
http://mail.python.org/mailman/listinfo/python-list


Re: older pythons

2009-07-09 Thread superpollo

Lie Ryan wrote:


AFAIK, no major linux distributions have officially ported to python
3.x.


http://packages.debian.org/experimental/python3.1

thanks for help
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >