Re: [Tutor] Introduction to modelling with Python

2010-03-28 Thread Modulok
Could you further define 'modeling' in context?

Are you referring to using python in the context of 3D modeling, i.e.
computer aided design? If that be the case, python serves as an
embedded language for many 3D computer graphics programs. Everything
from Maya to Houdini use it as a command interface to automate things.
See the developer's documentation for whatever software you're using.

What kind of modeling?
-Modulok-

On 3/27/10, AG  wrote:
> Hi List
>
> I apologise in advance for the vagueness of this query, but I am looking
> for a decent modern introduction to modelling using Python.
> Specifically, I want something that is a good introduction (i.e. doesn't
> expect one to already be a maths/ statistics or a programming guru) and
> that has an ecology/ environmental science orientation.  The latter is
> desirable but not essential, as I suspect that once one understands the
> process of data abstraction and the other steps involved in modelling
> processes and scenarios, the thinking and skill sets are likely
> transferable.  However, if my assumption about this is incorrect, please
> let me know.
>
> If anyone knows of any resource (book or on-line) with a Python bent,
> please let me know.  I am preparing to begin applications to Ph.D.
> programs and most of what I am interested in doing requires some
> knowledge of modelling and Python also seems to be widely accepted as a
> programming language, so I am happy with that as I am in the process of
> teaching myself Python anyway.
>
> Thanks for any help, advice, etc.
>
> Cheers
>
> AG
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Prime numbers

2010-03-28 Thread Rafik Ouerchefani
On Sat, Mar 27, 2010 at 11:08 PM, yd  wrote:
>
> Having a problem finding the first 1000 prime numbers, here is my code:-
>
> print(2)
> n =3
> counter =1
> while counter <=1000:
>   for x in range(3,int((n**0.5)),2):
>     if n%x != 0:
>   print(n)
>   n+=1
>   counter+=1
>     else:
>   n+=1
>

you are dividing n by x so your while loop should be "while n <= 1000" right ?
here is the idea to find prime numbers.

loop n from 1 to 1000
 loop x from 1 to n
  if n % x == 0
   then increment counter
  if the counter is == 2, then x is dividable by only 1 and x => x
is a prime number


> The problem is, it prints 2 and then does nothing, yet if i try and close,
> it says program is still running do you want to kill it, is there a way to
> do this with lists, i know python has a prime function but i am not going to
> use it because i want to solve this problem without 'cheating'.Thanks.

well, asking here is cheating :-D

cheers,

-- Rafik
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Prime numbers

2010-03-28 Thread Luke Paireepinart
On Sat, Mar 27, 2010 at 5:08 PM, yd  wrote:

>
> Having a problem finding the first 1000 prime numbers, here is my code:-
>
> print(2)
> n =3
> counter =1
> while counter <=1000:
>   for x in range(3,int((n**0.5)),2):
> if n%x != 0:
>   print(n)
>   n+=1
>   counter+=1
> else:
>   n+=1
>
> The problem is, it prints 2 and then does nothing, yet if i try and close,
> it says program is still running do you want to kill it, is there a way to
> do this with lists, i know python has a prime function but i am not going to
> use it because i want to solve this problem without 'cheating'.Thanks.
>
>
> What 'problem' are you trying to solve?
In general, anytime you can use a premade solution, you are at an advantage,
not cheating.
That's one of the marks of a truly good programmer - being able to reuse as
much code as possible.
Unless it's a homework problem and he said "don't use the prime function"
because in this case, your goal is to learn how to write a prime function,
not to calculate primes.
I.E. it's the doing, not the task.  And if that's the case, please let us
know that it's homework.  We will still help you, we just follow certain
guidelines
when providing homework assistance so as not to "give it away" and still
allow you to reason / come up with the solution on your own, as your teacher
probably intended.

-Luke
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Introduction to modelling with Python

2010-03-28 Thread AG

Modulok wrote:

Could you further define 'modeling' in context?

Are you referring to using python in the context of 3D modeling, i.e.
computer aided design? If that be the case, python serves as an
embedded language for many 3D computer graphics programs. Everything
from Maya to Houdini use it as a command interface to automate things.
See the developer's documentation for whatever software you're using.

What kind of modeling?
-Modulok-

On 3/27/10, AG  wrote:
  

Hi List

I apologise in advance for the vagueness of this query, but I am looking
for a decent modern introduction to modelling using Python.
Specifically, I want something that is a good introduction (i.e. doesn't
expect one to already be a maths/ statistics or a programming guru) and
that has an ecology/ environmental science orientation.  The latter is
desirable but not essential, as I suspect that once one understands the
process of data abstraction and the other steps involved in modelling
processes and scenarios, the thinking and skill sets are likely
transferable.  However, if my assumption about this is incorrect, please
let me know.

If anyone knows of any resource (book or on-line) with a Python bent,
please let me know.  I am preparing to begin applications to Ph.D.
programs and most of what I am interested in doing requires some
knowledge of modelling and Python also seems to be widely accepted as a
programming language, so I am happy with that as I am in the process of
teaching myself Python anyway.

Thanks for any help, advice, etc.

Cheers

AG
___




Modulok

The modelling I was referring to is not about 3-D design, but about 
scenario modelling.  For example, to understand the impacts of climate 
change on particular bodies of water, given different circumstances 
(e.g. x% of rain in the preceding year, or prevailing winds, or y number 
of herd animals using the water resource, and/ or upstream engineering 
developments, etc.), the idea would be to (a) identify those aspects 
most relevant and least relevant and (b) to programme those elements 
according to certain parameters of fluctuation (perhaps OOP might be 
useful here), and then (c) to manipulate those values according to 
different scenarios.  These manipulations can then be replayed any 
number of times (e.g. a Monte Carlo treatment) to obtain their 
statistical average and probabilities.


The foregoing is possibly not the most elegant example, but hopefully 
gives you a clearer idea of what I was asking about.


Thanks for your interest.

AG

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] inter-module global variable

2010-03-28 Thread spir ☣
Hello,

I have a main module importing other modules and defining a top-level variable, 
call it 'w' [1]. I naively thought that the code from an imported module, when 
called from main, would know about w, but I have name errors. The initial trial 
looks as follows (this is just a sketch, the original is too big and 
complicated):

# imported "code" module
__all__ = ["NameLookup", "Literal", "Assignment", ...]

# main module
from parser import parser
from code import *
from scope import Scope, World
w = World()

This pattern failed as said above. So, I tried to "export" w:

# imported "code" module
__all__ = ["NameLookup", "Literal", "Assignment", ...]

# main module
from parser import parser
from scope import Scope, World
w = World()
import code #new
code.w = w  ### "export"
from code import *

And this works. I had the impression that the alteration of the "code" module 
object would not propagate to objects imported from "code". But it works. But I 
find this terribly unclear, fragile, and dangerous, for any reason. (I find 
this "dark", in fact ;-)
Would someone try to explain what actually happens in such case?
Also, why is a global variable not actually global, but in fact only "locally" 
global (at the module level)?
It's the first time I meet such an issue. What's wrong in my design to raise 
such a problem, if any?

My view is a follow: From the transparency point of view (like for function 
transparency), the classes in "code" should _receive_ as general parameter a 
pointer to 'w', before they do anything. In other words, the whole "code" 
module is like a python code chunk parameterized with w. If it would be a 
program, it would get w as command-line parameter, or from the user, or from a 
config file.
Then, all instanciations should be done using this pointer to w. Meaning, as a 
consequence, all code objects should hold a reference to 'w'. This could be 
made as follows:

# main module
import code
code.Code.w = w
from code import *

# "code" module
class Code(object):
w = None### to be exported from importing module
def __init__(self, w=Code.w):
# the param allows having a different w eg for testing
self.w = w
# for each kind of code things
class CodeThing(Code):
def __init__(self, args):
Code.__init__(self)
... use args ...
   def do(self, args):
   ... use args and self.w ...

But the '###' line looks like  an ugly trick to me. (Not the fact that it's a 
class attribute; as a contrary, I often use them eg for config, and find them a 
nice tool for clarity.) The issue is that Code.w has to be exported.
Also, this scheme is heavy (all these pointers in every living object.) 
Actually, code objects could read Code.w directly but this does not change much 
(and I lose transparency).
It's hard for me to be lucid on this topic. Is there a pythonic way?


Denis

[1] The app is a kind of interpreter for a custom language. Imported modules 
define classes for  objects representing elements of code (literal, assignment, 
...). Such objects are instanciated from parse tree nodes (conceptually, they 
*are* code nodes). 'w' is a kind of global scope -- say the state of the 
running program. Indeed, most code objects need to read/write in w.
Any comments on this model welcome. I have few knowledge on implementation of 
languages.


vit esse estrany ☣

spir.wikidot.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inter-module global variable

2010-03-28 Thread Steven D'Aprano
On Sun, 28 Mar 2010 08:31:57 pm spir ☣ wrote:
> Hello,
>
> I have a main module importing other modules and defining a top-level
> variable, call it 'w' [1]. I naively thought that the code from an
> imported module, when called from main, would know about w, 

Why would it?

If you write a module M, you can't control what names exist in the 
calling module, and you shouldn't have to. Imagine if you wrote a 
module containing a function f, and it was imported by another module 
also containing f, and then suddenly all your module's functions 
stopped working! This would be a disaster:

# mymodule.py
def f(n):
return n+1

def spam(n):
return "spam"*f(n)


# caller.py
def f(n):
return range(23, 45+n, 6)

from mymodule import spam
print spam(2)  # expect "spamspamspam", get TypeError instead


> but I 
> have name errors. The initial trial looks as follows (this is just a
> sketch, the original is too big and complicated):
>
> # imported "code" module
> __all__ = ["NameLookup", "Literal", "Assignment", ...]
>
> # main module
> from parser import parser

By the way, have you looked at PyParsing? This is considered by many to 
be the gold standard in Python parsing libraries.


> from code import *

This is discouraged strongly. What happens if the code module has 
something called parser? Or len?

> from scope import Scope, World
> w = World()
>
> This pattern failed as said above. 

What do you mean "failed"? Nothing you show is obviously broken.



> So, I tried to "export" w: 
>
> # imported "code" module
> __all__ = ["NameLookup", "Literal", "Assignment", ...]
>
> # main module
> from parser import parser
> from scope import Scope, World
> w = World()
> import code   #new
> code.w = w### "export"
> from code import *
>
> And this works. I had the impression that the alteration of the
> "code" module object would not propagate to objects imported from
> "code". But it works. 

It sounds like you are trying to write PHP code in Python.


> But I find this terribly unclear, fragile, and 
> dangerous, for any reason. (I find this "dark", in fact ;-) Would
> someone try to explain what actually happens in such case? 

Yep, sounds like PHP code :)

Every function and class in a module stores a reference to their 
enclosing globals, so that when you do this:

# module A.py
x = "Hello world"

def f():
print x


# module B.py
from A import f
f()
=> prints "Hello world" as expected.


You don't have to do anything to make this work: every class and 
function knows what namespace it belongs to.

I can only imagine you're trying to do this:

# module A.py
x = "Hello world"

def f():
print x


# module B.py
x = "Goodbye cruel world!"
from A import f
f()
=> prints "Goodbye cruel world!"


This is bad design. You might think you need it, but in the long run you 
will regret it. You are mixing up arguments and globals. If you want 
the result of f() to depend on the local value of x, then make it take 
an argument:

def f(x):
print x

and call it:

f(x)


http://c2.com/cgi/wiki?GlobalVariablesAreBad
http://discuss.joelonsoftware.com/default.asp?design.4.249182.18



> Also, why 
> is a global variable not actually global, but in fact only "locally"
> global (at the module level)? It's the first time I meet such an
> issue. What's wrong in my design to raise such a problem, if any?

In Python, that is a deliberate choice. All globals are deliberately 
global to the module. The closest thing to "globally global" is the 
builtins namespace, which is where builtins like len, map, str, etc. 
are found.

Any design which relies on modifying global variables is flawed. Global 
variables are a poor design:

http://weblogs.asp.net/wallen/archive/2003/05/08/6750.aspx

Slightly better than global variables is a design where you use a module 
or class as a namespace, put all your globals in that namespace, then 
pass it to your other classes as an argument:

class SettingsNamespace:
pass

settings = SettingsNamespace()
settings.x = 42
settings.y = 23
settings.z = "magic"

instance = MyOtherClass(a, b, c, settings)

This is still problematic. For example, if I change settings.x, will the 
result of MyOtherClass be different? Maybe, maybe not... you have to 
dig deep into the code to know which settings are used and which are 
not, and you never know if an innocent-looking call to a function or 
class will modify your settings and break things.



> My view is a follow: From the transparency point of view (like for
> function transparency), the classes in "code" should _receive_ as
> general parameter a pointer to 'w', before they do anything.

Yes, this is better than "really global" globals, but not a lot better.


> In other 
> words, the whole "code" module is like a python code chunk
> parameterized with w. If it would be a program, it would get w as
> command-line parameter, or from the user, or from a config file.
> Then, all instanciations should be done using this pointer to 

Re: [Tutor] Prime numbers

2010-03-28 Thread yd
>
>
> > What 'problem' are you trying to solve?
> In general, anytime you can use a premade solution, you are at an
> advantage,
> not cheating.
> That's one of the marks of a truly good programmer - being able to reuse as
> much code as possible.
> Unless it's a homework problem and he said "don't use the prime function"
> because in this case, your goal is to learn how to write a prime function,
> not to calculate primes.
> I.E. it's the doing, not the task.  And if that's the case, please let us
> know that it's homework.  We will still help you, we just follow certain
> guidelines
> when providing homework assistance so as not to "give it away" and still
> allow you to reason / come up with the solution on your own, as your
> teacher
> probably intended.
>


>
> -Luke
>
It's not homework i just want to be able to convert my algorithm into good
code, and the only way to do that is by actually writing it. I'm just
writing it to learn how it's done.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inter-module global variable

2010-03-28 Thread Dave Angel

spir # wrote:

Hello,

I have a main module importing other modules and defining a top-level variable, 
call it 'w' [1]. I naively thought that the code from an imported module, when 
called from main, would know about w, but I have name errors. The initial trial 
looks as follows (this is just a sketch, the original is too big and 
complicated):

# imported "code" module
__all__ ="NameLookup", "Literal", "Assignment", ...]

# main module
from parser import parser
from code import *
from scope import Scope, World
w = World()

This pattern failed as said above. So, I tried to "export" w:

# imported "code" module
__all__ ="NameLookup", "Literal", "Assignment", ...]

# main module
from parser import parser
from scope import Scope, World
w = World()
import code #new
code.w = w  ### "export"
from code import *

And this works. I had the impression that the alteration of the "code" module object would not 
propagate to objects imported from "code". But it works. But I find this terribly unclear, fragile, 
and dangerous, for any reason. (I find this "dark", in fact ;-)
Would someone try to explain what actually happens in such case?
Also, why is a global variable not actually global, but in fact only "locally" 
global (at the module level)?
It's the first time I meet such an issue. What's wrong in my design to raise 
such a problem, if any?

My view is a follow: From the transparency point of view (like for function transparency), the 
classes in "code" should _receive_ as general parameter a pointer to 'w', before they do 
anything. In other words, the whole "code" module is like a python code chunk 
parameterized with w. If it would be a program, it would get w as command-line parameter, or from 
the user, or from a config file.
Then, all instanciations should be done using this pointer to w. Meaning, as a 
consequence, all code objects should hold a reference to 'w'. This could be 
made as follows:

# main module
import code
code.Code.w =
from code import *

# "code" module
class Code(object):
w =None ### to be exported from importing module
def __init__(self, w=Code.w):
# the param allows having a different w eg for testing
self.w =
# for each kind of code things
class CodeThing(Code):
def __init__(self, args):
Code.__init__(self)
... use args ...
   def do(self, args):
   ... use args and self.w ...

But the '###' line looks like  an ugly trick to me. (Not the fact that it's a 
class attribute; as a contrary, I often use them eg for config, and find them a 
nice tool for clarity.) The issue is that Code.w has to be exported.
Also, this scheme is heavy (all these pointers in every living object.) 
Actually, code objects could read Code.w directly but this does not change much 
(and I lose transparency).
It's hard for me to be lucid on this topic. Is there a pythonic way?


Denis

[1] The app is a kind of interpreter for a custom language. Imported modules 
define classes for  objects representing elements of code (literal, assignment, 
...). Such objects are instanciated from parse tree nodes (conceptually, they 
*are* code nodes). 'w' is a kind of global scope -- say the state of the 
running program. Indeed, most code objects need to read/write in w.
Any comments on this model welcome. I have few knowledge on implementation of 
languages.


vit esse estrany ☣

spir.wikidot.com

  
The word 'global' is indeed unfortunate for those coming to python from 
other languages. In Python, it does just mean global to a single module. 
If code in other modules needs to access your 'global variable' they 
need normally need it to be passed to them.


If you really need a program-global value, then create a new module just 
for the purpose, and define it there. Your main program can initialize 
it, other modules can access it in the usual way, and everybody's happy. 
In general, you want import and initialization to happen in a 
non-recursive way. So an imported module should not look back at you for 
values. If you want it to know about a value, pass it, or assign it for 
them.


But Python does not have pointers. And you're using pointer terminology. 
Without specifying the type of w, you give us no clue whether you're 
setting yourself up for failure. For example, the first time somebody 
does a w= newvalue they have broken the connection with other module's w 
variable. If the object is mutable (such as a list), and somebody 
changes it by using w.append() or w[4] = newvalue, then no problem.


You have defined a class attribute w, and an instance attribute w, and a 
module variable w in your main script. Do these values all want to stay 
in synch as you change values? Or is it a constant that's just set up 
once? Or some combination, where existing objects want the original 
value, but new ones created after you change it will themselves get the 
value at the time of creation? You can get any of these b

Re: [Tutor] python magazine

2010-03-28 Thread Lowell Tackett

>From the virtual desk of Lowell Tackett  



--- On Sat, 3/27/10, Dave Angel  wrote:

> From: Dave Angel 
> Subject: Re: [Tutor] python magazine
> To: "Lowell Tackett" 
> Cc: "Benno Lang" , tutor@python.org
> Date: Saturday, March 27, 2010, 6:12 AM
> 
> 
> Lowell Tackett wrote:
> > >From the virtual desk of Lowell Tackett  
> > 
> > --- On Fri, 3/26/10, Benno Lang 
> wrote:
> > 
> > From: Benno Lang 
> > Subject: Re: [Tutor] python magazine
> > To: "Lowell Tackett" 
> > Cc: tutor@python.org,
> "Bala subramanian" 
> > Date: Friday, March 26, 2010, 8:38 PM
> > 
> > On 27 March 2010 00:33, Lowell Tackett 
> wrote:
> >   
> >> The Python Magazine people have now got a Twitter
> site--which includes a perhaps [telling] misspelling.
> >> 
> > Obviously that's why they're looking for a chief
> editor - maybe it's
> > even a deliberate ploy.
> > 
> > I'm not sure if this affects others, but to me your
> replies appear
> > inside the quoted section of your mail, rather than
> beneath it. Would
> > you mind writing plain text emails to avoid this
> issue?
> > 
> > Thanks,
> > benno
> > 
> > Like this...?
> > 
> > 
> >   
> No, there's still a problem.  You'll notice in this
> message that there are ">" symbols in front of your lines
> and benno's, and ">>" symbols in front of
> Lowell's.  (Some email readers will turn the > into
> vertical bar, but the effect is the same).  Your email
> program should be adding those upon a reply, so that your
> own message has one less > than the one to which you're
> replying.  Then everyone reading can see who wrote
> what, based on how many ">" or bars precede the
> respective lines.  Quotes from older messages have more
> of them.
> 
> Are you using "Reply-All" in your email program?  Or
> are you constructing a new message with copy/paste?
> 
> What email are you using?  Maybe it's a configuration
> setting somebody could help with.
> 
> DaveA
> 
> 
Don't really know what I'm doing wrong (or right).  Just using the [email] 
tools that have been made available to me thru Yahoo mail and Firefox.  I began 
this text below your submission and "signature", and I'm using plain text, as 
suggested by a previous comment.  Don't know what else I could embellish this 
effort with.


  

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Introduction to modelling with Python

2010-03-28 Thread spir ☣
On Sun, 28 Mar 2010 10:26:43 +0100
AG  wrote:

> Modulok wrote:
> > Could you further define 'modeling' in context?
[...]

> The modelling I was referring to is not about 3-D design, but about 
> scenario modelling.  For example, to understand the impacts of climate 
> change on particular bodies of water, given different circumstances 
> (e.g. x% of rain in the preceding year, or prevailing winds, or y number 
> of herd animals using the water resource, and/ or upstream engineering 
> developments, etc.), the idea would be to (a) identify those aspects 
> most relevant and least relevant and (b) to programme those elements 
> according to certain parameters of fluctuation (perhaps OOP might be 
> useful here), and then (c) to manipulate those values according to 
> different scenarios.  These manipulations can then be replayed any 
> number of times (e.g. a Monte Carlo treatment) to obtain their 
> statistical average and probabilities.
> 
> The foregoing is possibly not the most elegant example, but hopefully 
> gives you a clearer idea of what I was asking about.
> 
> Thanks for your interest.
> 
> AG

Note: this is personal point of view. Just hope you & others find it 
interesting.

Programming, for me, is just modelling and coding; in a sense of "modelling" 
similar to the one you give, which is also close to the sense used in 
scientific/research activity, as I understand it. The main particuliarity of 
programming is that the target is a machine, which implies good (accuracy) and 
bad (rigidity) requirements.

More precisely, I call "model" the mental picture we have of a "topic" -- more 
or less accurate, indeed, according to the guy's lucidity on the topic (clarity 
of mind) and to the requirements. A program is then a given expression of the 
programmer's model of the topic in a given language; and a running program is a 
simulation of the topic according to the model. The program may itself be more 
or less accurate in the sense there may be some distortion between the model 
and the program's actual "semantics".
In programming practice, except in trivial cases, there is a constant move 
forth & back between modelling and coding, because while coding and testing we 
learn about the topic, get a clearer view, and modify the model. Which in turn 
requires updating the program, building a kind of feedback loop, until we are 
satisfied with the model, the program, the simulation (*).

Like any language (--> Sapir-Worf hypothesis), a programming language certainly 
strongly influences the way we basically *think* about things, not only how we 
express it, meaning it will filter our ability to model. For the best and/or 
for the worse. We may simply not be able to model independently of one (or 
more) given language(s). After some years programming in Java, a programmer 
switching to Python will produce not only Java code reworded into Python (which 
is ugly ;-), but Java *thought* (model) (which is wrong ;-).

To relate this with your request, I thus think learning to model in Python is 
just learning to program well in Python, which itself is just a specialisation 
of learning to program well. If you really want this, and have enough time, 
then for me you should instead learn to program using various languages, as 
different as possible, so as to learn various modelling patterns. And apply 
those languages on a variety of topics, including some in your own field. A 
life time's job!
Again, this is just my opinion.


Denis

(*) I like the word simulation here because it does not imply the topic to have 
anything to do with reality. Instead, it can be imaginary, in most cases real 
is at most a referent. Think at games (they exist only in the author and 
players' minds) or even an editor (the legacy way of writing just provides a 
metaphor). In many cases, the simulation is its own sense, meaning the 
simulation *is* the topic, there is no referent.


vit esse estrany ☣

spir.wikidot.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Prime numbers

2010-03-28 Thread Lie Ryan
On 03/28/2010 09:57 PM, yd wrote:
> It's not homework i just want to be able to convert my algorithm into
> good code, and the only way to do that is by actually writing it. I'm
> just writing it to learn how it's done.

In most cases, when:
1) the code is effective (i.e. it always gives correct answer)
2) the code is efficient (i.e. it terminates in a reasonable amount of
time, and uses a reasonable amount of memory)
3) you can articulate why you write your code in a particular way, can
describe why the algorithm works, and can answer when challenged
4) you and other people can read your code six months later with
relatively little difficulty
5) your code is as concise as possible, without affecting #4 (e.g.
leveraged most of the side work to another library, used common idioms
in the appropriate situations, etc)

in most case, you probably have written a good code.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python magazine

2010-03-28 Thread Dave Angel

Lowell Tackett wrote:
>From the virtual desk of Lowell Tackett  




--- On Sat, 3/27/10, Dave Angel  wrote:

  

From: Dave Angel 
Subject: Re: [Tutor] python magazine
To: "Lowell Tackett" 
Cc: "Benno Lang" , tutor@python.org
Date: Saturday, March 27, 2010, 6:12 AM


Lowell Tackett wrote:

>From the virtual desk of Lowell Tackett  


--- On Fri, 3/26/10, Benno Lang 
  

wrote:


From: Benno Lang 
Subject: Re: [Tutor] python magazine
To: "Lowell Tackett" 
Cc: tutor@python.org,
  

"Bala subramanian" 


Date: Friday, March 26, 2010, 8:38 PM

On 27 March 2010 00:33, Lowell Tackett 
  

wrote:

  
  

The Python Magazine people have now got a Twitter


site--which includes a perhaps [telling] misspelling.




Obviously that's why they're looking for a chief
  

editor - maybe it's


even a deliberate ploy.

I'm not sure if this affects others, but to me your
  

replies appear


inside the quoted section of your mail, rather than
  

beneath it. Would


you mind writing plain text emails to avoid this
  

issue?


Thanks,
benno

Like this...?


  
  

No, there's still a problem.  You'll notice in this
message that there are ">" symbols in front of your lines
and benno's, and ">>" symbols in front of
Lowell's.  (Some email readers will turn the > into
vertical bar, but the effect is the same).  Your email
program should be adding those upon a reply, so that your
own message has one less > than the one to which you're
replying.  Then everyone reading can see who wrote
what, based on how many ">" or bars precede the
respective lines.  Quotes from older messages have more
of them.

Are you using "Reply-All" in your email program?  Or
are you constructing a new message with copy/paste?

What email are you using?  Maybe it's a configuration
setting somebody could help with.

DaveA




Don't really know what I'm doing wrong (or right).  Just using the [email] tools that 
have been made available to me thru Yahoo mail and Firefox.  I began this text below your 
submission and "signature", and I'm using plain text, as suggested by a 
previous comment.  Don't know what else I could embellish this effort with.


  
This time it worked great.  You can see my comments at outermost level, 
with yours indented by one, and my previous one indented two, etc.


DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inter-module global variable

2010-03-28 Thread spir ☣

On Sun, 28 Mar 2010 21:50:46 +1100
Steven D'Aprano  wrote:

> On Sun, 28 Mar 2010 08:31:57 pm spir ☣ wrote:
> > Hello,
> >
> > I have a main module importing other modules and defining a top-level
> > variable, call it 'w' [1]. I naively thought that the code from an
> > imported module, when called from main, would know about w, 
> 
> Why would it?
> 
> If you write a module M, you can't control what names exist in the 
> calling module, and you shouldn't have to. Imagine if you wrote a 
> module containing a function f, and it was imported by another module 
> also containing f, and then suddenly all your module's functions 
> stopped working! This would be a disaster:

Right, this makes sense, indeed, thank you for showing it clearly.

> > but I 
> > have name errors. The initial trial looks as follows (this is just a
> > sketch, the original is too big and complicated):
> >
> > # imported "code" module
> > __all__ = ["NameLookup", "Literal", "Assignment", ...]
> >
> > # main module
> > from parser import parser
> 
> By the way, have you looked at PyParsing? This is considered by many to 
> be the gold standard in Python parsing libraries.

Yes, I used to know pyparsing very well... (Including most of its internal 
arcanes. In fact I wrote several matching/parsing/processing libraries after 
having worked with it. This because, on one hand, I like pyparsing base 
approach of a "live" code grammar, but on the other hand its way of doing does 
not fit my brain.)
 
> > from code import *
> 
> This is discouraged strongly. What happens if the code module has 
> something called parser? Or len?

Yes, I know. But as you can read above, the exported names are defined (and are 
all classes). Also, the importing module only does one thing, which is 
precisely to use thoses imported names. Similarly, a grammar/parser definition 
imports all pattern classes (from my own matching library, like it would from 
pyparsing) into a module dedicated to the definition of the language. I 
consider this a good practice as long as it is done consciously.
There is no difference, I guess, betweeen

# "matchBox" matching module
__all__ = [all pattern class names + "Parser"]
# parser module
from matchBox import *

and

# parser module
from matchBox import 

> > from scope import Scope, World
> > w = World()
> >
> > This pattern failed as said above. 
> 
> What do you mean "failed"? Nothing you show is obviously broken.

I mean the name error about 'w'.

> > So, I tried to "export" w: 
> >
> > # imported "code" module
> > __all__ = ["NameLookup", "Literal", "Assignment", ...]
> >
> > # main module
> > from parser import parser
> > from scope import Scope, World
> > w = World()
> > import code #new
> > code.w = w  ### "export"
> > from code import *
> >
> > And this works. I had the impression that the alteration of the
> > "code" module object would not propagate to objects imported from
> > "code". But it works. 
> 
> It sounds like you are trying to write PHP code in Python.

Know about nothing about PHP.
 
> > But I find this terribly unclear, fragile, and 
> > dangerous, for any reason. (I find this "dark", in fact ;-) Would
> > someone try to explain what actually happens in such case? 
> 
> Yep, sounds like PHP code :)
> 
> Every function and class in a module stores a reference to their 
> enclosing globals, so that when you do this:
> 
> # module A.py
> x = "Hello world"
> 
> def f():
> print x
> 
> 
> # module B.py
> from A import f
> f()
> => prints "Hello world" as expected.
> 
> 
> You don't have to do anything to make this work: every class and 
> function knows what namespace it belongs to.

All right.

> I can only imagine you're trying to do this:
> 
> # module A.py
> x = "Hello world"
> 
> def f():
> print x
> 
> 
> # module B.py
> x = "Goodbye cruel world!"
> from A import f
> f()
> => prints "Goodbye cruel world!"

Hem, more or less. but the main difference is that x is not and cannot be 
defined in A (except for a fake initialisation to None, like for an instance 
var). It's actual value can only come from the module that import A, here B.

> This is bad design. You might think you need it, but in the long run you 
> will regret it. You are mixing up arguments and globals. If you want 
> the result of f() to depend on the local value of x, then make it take 
> an argument:
> 
> def f(x):
> print x
> 
> and call it:
> 
> f(x)
> 
> 
> http://c2.com/cgi/wiki?GlobalVariablesAreBad
> http://discuss.joelonsoftware.com/default.asp?design.4.249182.18

Gonna follow the links as soon as I have time.

> > Also, why 
> > is a global variable not actually global, but in fact only "locally"
> > global (at the module level)? It's the first time I meet such an
> > issue. What's wrong in my design to raise such a problem, if any?
> 
> In Python, that is a deliberate choice. All globals are deliberately 
> global to the module. The closest thing to "globally global" is the 
> builtins namespace, 

Re: [Tutor] Introduction to modelling with Python

2010-03-28 Thread Eike Welk
On Saturday March 27 2010 16:21:26 AG wrote:
> I apologise in advance for the vagueness of this query, but I am looking
> for a decent modern introduction to modelling using Python.
> Specifically, I want something that is a good introduction (i.e. doesn't
> expect one to already be a maths/ statistics or a programming guru) and
> that has an ecology/ environmental science orientation. 

You should look at the book "Python Scripting for Computational Science" by 
Hans Petter Langtangen:
http://www.amazon.com/Python-Scripting-Computational-Science-
Engineering/dp/3540435085
http://books.google.com/books?id=YEoiYr4H2A0C&printsec=frontcover&dq="Python+Scripting+for+Computational+Science"&source=bl&ots=ovp_JKREiY&sig=tJkigCLDqS6voOOjmL4xDxw0roM&hl=en&ei=OlWvS8PmE4r94Aa42vzgDw&sa=X&oi=book_result&ct=result&resnum=5&ved=0CBEQ6AEwBA#v=onepage&q=&f=false

It is an introduction to the Python language, and to a big number of tools for 
numerical computations. The book assumes that you have already some practice 
in writing computer programs. 

The book is not oriented towards ecology, the examples are from mechanical 
engineering. 

The book is however a bit dated, it's from 2004. Therefore many examples will 
need to be slightly altered to work with the current versions of the libraries 
that they use. 



Alternatively you could ask your question on the Numpy/Scipy mailing lists. 
These lists are frequented by scientists that use Python for their 
computations.  
http://www.scipy.org/Mailing_Lists



Eike.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] automatic output file naming scheme

2010-03-28 Thread kevin parks
okay. I got the subprocess bit to work and i have os walk doing its walk. But 
now for something i did not think about until i started to think about how to 
fit these two bits to work together.

os walk is going to traverse my dirs from some given starting point and process 
files that it finds that fit my criteria. So i my case it will look for all 
sound files in a given directly structure and then call sox and do a 
conversion. This part i can already probably do just by combining the working 
code that i have … but now i need to have some kind of automagic naming scheme 
that creates an output file name that is based on the input name but is unique, 
either adding a number or suffix before the file extension, or even a time 
stamp. Since we want to create file names that are unique and not clobber 
existing files, but also will tells us something meaningful about how the file 
was created so that finding:

foo01.aif or foo.1.aif would yield something like foo-out01.aif or 
foo01-out.aif or something similar.

How can you do such a thing in python? is there some elegant way to take the 
input file name and combine it with some other string to create the output file 
name?

-kp


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "IOError: [Errno 32] Broken pipe" when running python with cron (alternatives?)

2010-03-28 Thread Emile van Sebille

On 3/27/2010 5:45 AM Karjer Jdfjdf said...

I have made an extensive script that runs fine when started from the command 
line or IDLE.

When I try to run it with cron it keeps giving errors:


Often when I have trouble running scripts from cron it's because 
something in the environment is different.


Try restructuring the way you start the script from cron.  Say your cron 
entry looks like:


* * * * * someone /usr/local/bin/myscript.py

Then something like:

env > /usr/local/bin/myscript.sh
echo /usr/local/bin/myscript.py >> /usr/local/bin/myscript.sh
chmod a+x /usr/local/bin/myscript.py

and change cron to

* * * * * someone /usr/local/bin/myscript.sh

and see if that helps.

Emile





Error in sys.exitfunc:
Traceback (most recent call last):
   File "/usr/lib/python2.6/atexit.py", line 24, in _run_exitfuncs
 func(*targs, **kargs)
   File "/usr/lib/python2.6/logging/__init__.py", line 1508, in shutdown
 h.flush()
   File "/usr/lib/python2.6/logging/__init__.py", line 754, in flush
 self.stream.flush()
IOError: [Errno 32] Broken pipe


The script has the following structure:
1. retrieves data from database 1
2. modifies the data
3. inserts the modified data in another database

In a previous script I solved this problem with directing the stdout and stderr 
to /dev/null, but doing this isn't possible because I use pickle and write some 
data to files. It seems to have anything to do with the stdout/stderr and cron, 
but after a lot of googling I don't have any clues how to fix this.

How can I solve this? Does anybody know how to solve this or is there a 
python-friendly alternative to cron that I can use.







___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] automatic output file naming scheme

2010-03-28 Thread Emile van Sebille

On 3/28/2010 8:44 AM kevin parks said...

okay. I got the subprocess bit to work and i have os walk doing its walk. But 
now for something i did not think about until i started to think about how to 
fit these two bits to work together.

os walk is going to traverse my dirs from some given starting point and process 
files that it finds that fit my criteria. So i my case it will look for all 
sound files in a given directly structure and then call sox and do a 
conversion. This part i can already probably do just by combining the working 
code that i have … but now i need to have some kind of automagic naming scheme 
that creates an output file name that is based on the input name but is unique, 
either adding a number or suffix before the file extension, or even a time 
stamp. Since we want to create file names that are unique and not clobber 
existing files, but also will tells us something meaningful about how the file 
was created so that finding:

foo01.aif or foo.1.aif would yield something like foo-out01.aif or 
foo01-out.aif or something similar.

How can you do such a thing in python? is there some elegant way to take the 
input file name and combine it with some other string to create the output file 
name?


So you've really got two issues -- building a new name to use, and 
confirming it's unique.


You can build a new name with the replace method of strings or 
concatenating pieces of the new name using join or string interpolation.


os.path has some functions you may find helpful:






-kp


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] automatic output file naming scheme

2010-03-28 Thread Emile van Sebille

On 3/28/2010 8:44 AM kevin parks said...

okay. I got the subprocess bit to work and i have os walk doing its walk. But 
now for something i did not think about until i started to think about how to 
fit these two bits to work together.

os walk is going to traverse my dirs from some given starting point and process 
files that it finds that fit my criteria. So i my case it will look for all 
sound files in a given directly structure and then call sox and do a 
conversion. This part i can already probably do just by combining the working 
code that i have … but now i need to have some kind of automagic naming scheme 
that creates an output file name that is based on the input name but is unique, 
either adding a number or suffix before the file extension, or even a time 
stamp. Since we want to create file names that are unique and not clobber 
existing files, but also will tells us something meaningful about how the file 
was created so that finding:

foo01.aif or foo.1.aif would yield something like foo-out01.aif or 
foo01-out.aif or something similar.

How can you do such a thing in python? is there some elegant way to take the 
input file name and combine it with some other string to create the output file 
name?


So you've really got two issues -- building a new name to use, and 
confirming it's unique.


You can build a new name with the replace method of strings or 
concatenating pieces of the new name using join or string interpolation.


>>> sourcefile = "/home/someone/somedir/foo01.aif"

>>> sourcefile.replace(".aif","-001.aif")
'/home/someone/somedir/foo01-001.aif'

or

>>> sourcefile.replace(".aif","-%03d.aif" % sequence)


os.path has some functions you may find helpful:

>>> os.path.split(sourcefile)
('/home/someone/somedir', 'foo01.aif')
>>> os.path.basename(sourcefile)
'foo01.aif'
>>> os.path.splitext(sourcefile)
('/home/someone/somedir/foo01', '.aif')
>>> os.path.exists(sourcefile)
False

HTH,

Emile

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] First extension

2010-03-28 Thread Emile van Sebille

On 3/26/2010 7:03 PM James Reynolds said...

Hello All,

I'm trying to write my first extension module, and I am getting the
following error in my command prompt and I was hoping you all could help me.


Hi James,

You'll probably get further asking on the setuptools support list. 
Checking http://pypi.python.org/pypi/setuptools I see links to the list 
at http://mail.python.org/pipermail/distutils-sig/


Those are the guys that will want this info and will most likely help 
you work through it.


HTH,

Emile




I have taken the following steps already:


1. My path is set for mingw/bin as well as python31.
2. There is a file in my disutils folder called disutils.cfg that says
[build] compiler = mingw32
3. The instructions in the 3.1 documentation state the following: "These
instructions only apply if you’re using a version of Python prior to 2.4.1
with a MinGW prior to 3.0.0 (with binutils-2.13.90-20030111-
   1. http://docs.python.org/py3k/install/index.html
   2. I am using Python 3.1 and the latest MinGW.
4. I tested gcc/mingw by doing C:\python31>gcc -shared pdv.c -o pdv.dll
and the test was succesful (or at least I was not given any errors while
doing the compile)
5. I searched on the internet and the closest thing I can find is the
following: http://bugs.python.org/issue4709


Below you will find the following

One, the error report
two,my setup.py file
three, the file I am trying to turn into a python extension module by
running the following two commands:

python setup.py build
python setup.py install


#1


Microsoft Windows [Version 6.1.7600]

Copyright (c) 2009 Microsoft Corporation.  All rights reserved.



c:\Python31\Lib\finance>python setup.py build


running build

running build_ext

building 'finance' extension

creating build

creating build\temp.win-amd64-3.1

creating build\temp.win-amd64-3.1\Release

C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\Python31\include

-IC:\Pytho


n31\PC -c finance.c -o build\temp.win-amd64-3.1\Release\finance.o

finance.c: In function `PyInit_finance':

finance.c:31: warning: implicit declaration of function `Py_Module_Create'

finance.c:31: warning: return makes pointer from integer without a cast

writing build\temp.win-amd64-3.1\Release\finance.def

creating build\lib.win-amd64-3.1

C:\MinGW\bin\gcc.exe -mno-cygwin -shared -s

build\temp.win-amd64-3.1\Release\fin


ance.o build\temp.win-amd64-3.1\Release\finance.def -LC:\Python31\libs

-LC:\Pyth


on31\PCbuild\amd64 -lpython31 -lmsvcr90 -o

build\lib.win-amd64-3.1\finance.pyd


build\temp.win-amd64-3.1\Release\finance.o:finance.c:(.text+0x2b): undefined

ref


erence to `_imp__PyArg_ParseTuple'

build\temp.win-amd64-3.1\Release\finance.o:finance.c:(.text+0x5c): undefined

ref


erence to `_imp__Py_BuildValue'

build\temp.win-amd64-3.1\Release\finance.o:finance.c:(.text+0x74): undefined

ref


erence to `Py_Module_Create'

collect2: ld returned 1 exit status

error: command 'gcc' failed with exit status 1



c:\Python31\Lib\finance>




#2


from distutils.core import setup, Extension



setup(name = "finance",


   version = "1.0",

   ext_modules = [Extension("finance", ["finance.c"])])



#3

#include

#include



static PyObject *


pdv(PyObject *self, PyObject *args)

{

double value, rate, timex, denom, pdvx;

if (!PyArg_ParseTuple(args, "ddd",&value,&rate,&timex))

return NULL;

 denom = (double) pow ((1 + rate), (timex));

 pdvx = value / denom;

return Py_BuildValue("d", pdvx);

}

PyMethodDef pdvMethods[] = {

 {"pdv", pdv, METH_VARARGS, "Returns the Present Discounted Value given

of a single future value"},


 {NULL, NULL, 0, NULL}

};



static struct PyModuleDef financemodule = {


PyModuleDef_HEAD_INIT,

"finance",   /* name of module */

NULL, /* module documentation, may be NULL */

-1,   /* size of per-interpreter state of the module,

 or -1 if the module keeps state in global variables. */

pdvMethods

};



PyMODINIT_FUNC


PyInit_finance(void)

{

 return Py_Module_Create(&financemodule);

}




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] ask

2010-03-28 Thread Shurui Liu (Aaron Liu)
Since English is not my native language, so I got confused by some
requirement of my assignment. I already done, just want to make sure what I
did is what the assignment required, thank you!

BTW, I don't know how to do this:
If I want to fix some wrong words in a text file, how can I print out the
right/fixed text file? Like this:
My favor colour is blue. → My favourite color is blue. (Just print out the
right thing directly)

Thank you!

assignment:

1 Write a Python program named british2american.py
 that reads the contents of a text file, looks for occurances of
uniquely British spelling, and translates the occurances into the
acceptes American spelling.

1
Specifically, you will be looking for the following words: colour,
analyse, memorise, centre and recognise. If found, they are to be
replaced with color, analyze, memorize, center and recognize.

1 The following is needed for you to write your program:

1 the name of the file containing the text to be translated is storyBrit.txt
 and it is to be located in your cset1100py directory. Copy it from this
link 
 to the designated location.

1 your program, british2american.py, should be located in your cset1100py
 directory on et791

1 the name of the file containing the translated output is storyAmer.txt
 and it is to located in a subdirectory off your cset1100py directory named
assign19, that is ./cset1100py/assign19/storyAmer.txt

1 the original file, storyBrit.txt, should be left unchanges
This is british2american.py
# Translate wrong British words
#Create an empty file
print "\nReading characters from the file."
raw_input("Press enter then we can move on:")
text_file = open("storyBrit.txt", "r+")
whole_thing = text_file.read()
print whole_thing
raw_input("Press enter then we can move on:")
print "\nWe are gonna find out the wrong British words."
# Press enter and change the wrong words
if "colour" in whole_thing:
print "The wrong word is 'colour' and the right word is 'color'"
if "analyse" in whole_thing:
print "the wrong word is 'analyse' and the right word is 'analyze'"
if "memorise" in whole_thing:
print "the wrong word is 'memorise' and the right word is 'memorize'"
if "centre" in whole_thing:
print "the wrong word is 'centre' and the right word is 'center'"
if "recognise" in whole_thing:
print "the wrong word is 'recognise' and the right word is 'recognize'"
if "honour" in whole_thing:
print "the wrong word is 'honour' and the right word is 'honor'"
# We are gonna save the right answer to storyAmer.txt
w = open('storyAmer.txt', 'w')
w.write('I am really glad that I took CSET 1100.')
w.write('\n')
w.write('We get to analyse all sorts of real-world problems.\n')
w.write('\n')
w.write('We also have to memorize some programming language syntax.')
w.write('\n')
w.write('But, the center of our focus is game programming and it is fun.')
w.write('\n')
w.write('Our instructor adds color to his lectures that make them
interesting.')
w.write('\n')
w.write('It is an honor to be part of this class!')
w.close()

This is storyAmer.txt(right one):
I am really glad that I took CSET 1100.We get to analyze all sorts of
real-world problems.We also have to memorize some programming language
syntax. But, the center of our focus is game programming and it is fun.Our
instructor adds colour to his lectures that make them interesting.It is an
honor to be part of this class!

This is storyBrit.txt(wrong one):
I am really glad that I took CSET 1100.We get to analise all sorts of
real-world problems.We also have to memorise some programming language
syntax. But, the centre of our focus is game programming and it is fun.Our
instructor adds colour to his lectures that make them interesting.It is an
honour to be part of this class!


Thank you very much!



-- 
Shurui Liu (Aaron Liu)
Computer Science & Engineering Technology
University of Toledo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ask

2010-03-28 Thread Shurui Liu (Aaron Liu)
You know what, I just don't understand this line:
the name of the file containing the translated output is storyAmer.txt
and it is to located.


I don't know what kind of translated output he need. I guess:

   1. the name of the file containing the translated output is *
   storyAmer.txt* and it is to located in a subdirectory off your cset1100py
   *assign19*, that is *./cset1100py/assign19/storyAmer.txt* directory named


What kind of translated output do you want?

(1) A list of wrong words and a list of right words, like this:

Wrong words in the text are: ..

 Right words should be: ..



OR



(2) The content of the text but has already been translated, like this:



I am really glad that I took CSET 1100.
We get to *analyze* all sorts of real-world problems.
We also have to *memorize* some programming language syntax.
But, the *center* of our focus is game programming and it is fun.
Our instructor adds *color* to his lectures that make them interesting.
It is an honour to be part of this class!



在 2010年3月28日 下午12:26,Shurui Liu (Aaron Liu) 写道:

> Since English is not my native language, so I got confused by some
> requirement of my assignment. I already done, just want to make sure what I
> did is what the assignment required, thank you!
>
> BTW, I don't know how to do this:
> If I want to fix some wrong words in a text file, how can I print out the
> right/fixed text file? Like this:
> My favor colour is blue. → My favourite color is blue. (Just print out the
> right thing directly)
>
> Thank you!
>
> assignment:
>
> 1 Write a Python program named british2american.py
>  that reads the contents of a text file, looks for occurances of uniquely 
> British spelling, and translates the occurances into the acceptes American 
> spelling.
>
> 1
> Specifically, you will be looking for the following words: colour, analyse, 
> memorise, centre and recognise. If found, they are to be
> replaced with color, analyze, memorize, center and recognize.
>
> 1 The following is needed for you to write your program:
>
> 1 the name of the file containing the text to be translated is
> storyBrit.txt
>  and it is to be located in your cset1100py directory. Copy it from this
> link 
>  to the designated location.
>
> 1 your program, british2american.py, should be located in your cset1100py
>  directory on et791
>
> 1 the name of the file containing the translated output is storyAmer.txt
>  and it is to located in a subdirectory off your cset1100py directory named
> assign19, that is ./cset1100py/assign19/storyAmer.txt
>
> 1 the original file, storyBrit.txt, should be left unchanges
> This is british2american.py
> # Translate wrong British words
> #Create an empty file
> print "\nReading characters from the file."
> raw_input("Press enter then we can move on:")
> text_file = open("storyBrit.txt", "r+")
> whole_thing = text_file.read()
> print whole_thing
> raw_input("Press enter then we can move on:")
> print "\nWe are gonna find out the wrong British words."
> # Press enter and change the wrong words
> if "colour" in whole_thing:
> print "The wrong word is 'colour' and the right word is 'color'"
> if "analyse" in whole_thing:
> print "the wrong word is 'analyse' and the right word is 'analyze'"
> if "memorise" in whole_thing:
> print "the wrong word is 'memorise' and the right word is 'memorize'"
> if "centre" in whole_thing:
> print "the wrong word is 'centre' and the right word is 'center'"
> if "recognise" in whole_thing:
> print "the wrong word is 'recognise' and the right word is 'recognize'"
> if "honour" in whole_thing:
> print "the wrong word is 'honour' and the right word is 'honor'"
> # We are gonna save the right answer to storyAmer.txt
> w = open('storyAmer.txt', 'w')
> w.write('I am really glad that I took CSET 1100.')
> w.write('\n')
> w.write('We get to analyse all sorts of real-world problems.\n')
> w.write('\n')
> w.write('We also have to memorize some programming language syntax.')
> w.write('\n')
> w.write('But, the center of our focus is game programming and it is fun.')
> w.write('\n')
> w.write('Our instructor adds color to his lectures that make them
> interesting.')
> w.write('\n')
> w.write('It is an honor to be part of this class!')
> w.close()
>
> This is storyAmer.txt(right one):
> I am really glad that I took CSET 1100.We get to analyze all sorts of
> real-world problems.We also have to memorize some programming language
> syntax. But, the center of our focus is game programming and it is fun.Our
> instructor adds colour to his lectures that make them interesting.It is an
> honor to be part of this class!
>
> This is storyBrit.txt(wrong one):
> I am really glad that I took CSET 1100.We get to analise all sorts of
> real-world problems.We also have to memorise some programming language
> syntax. But, the centre of our focus is game programming and it is fun.Our
> instructor adds colour to his lectures t

Re: [Tutor] Introduction to modelling with Python

2010-03-28 Thread AG

Eike Welk wrote:

On Saturday March 27 2010 16:21:26 AG wrote:
  

I apologise in advance for the vagueness of this query, but I am looking
for a decent modern introduction to modelling using Python.
Specifically, I want something that is a good introduction (i.e. doesn't
expect one to already be a maths/ statistics or a programming guru) and
that has an ecology/ environmental science orientation. 



You should look at the book "Python Scripting for Computational Science" by 
Hans Petter Langtangen:

http://www.amazon.com/Python-Scripting-Computational-Science-
Engineering/dp/3540435085
http://books.google.com/books?id=YEoiYr4H2A0C&printsec=frontcover&dq="Python+Scripting+for+Computational+Science"&source=bl&ots=ovp_JKREiY&sig=tJkigCLDqS6voOOjmL4xDxw0roM&hl=en&ei=OlWvS8PmE4r94Aa42vzgDw&sa=X&oi=book_result&ct=result&resnum=5&ved=0CBEQ6AEwBA#v=onepage&q=&f=false

It is an introduction to the Python language, and to a big number of tools for 
numerical computations. The book assumes that you have already some practice 
in writing computer programs. 

The book is not oriented towards ecology, the examples are from mechanical 
engineering. 

The book is however a bit dated, it's from 2004. Therefore many examples will 
need to be slightly altered to work with the current versions of the libraries 
that they use. 




Alternatively you could ask your question on the Numpy/Scipy mailing lists. 
These lists are frequented by scientists that use Python for their 
computations.  
http://www.scipy.org/Mailing_Lists




Eike.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

  


Now that's looking very much along the lines of what I had in mind 
Eike.  Very pricey ... might have to sit on that one for a while and 
scout around for a used copy.  I can certainly use the on-line resource 
for as many pages as it allows one to access until I either find a 
cheaper version or perhaps win a lottery!!


But, yep, this looks like what I had in mind - so anything else like 
this would be good as well.


Cheers

AG
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ask

2010-03-28 Thread Emile van Sebille
On 3/28/2010 10:28 AM Shurui Liu (Aaron Liu) said...
> You know what, I just don't understand this line:
> the name of the file containing the translated output is storyAmer.txt
> and it is to located.

It sounds to me like we wants you to read in the source(british)
version, swap in the american spellings, then write the resulting text
to storyAmer.txt

You might investigate the replace (1) method of strings and use it along
the lines of:

whole_thing = whole_thing.replace(british_spelling,american_spelling)

Also, look up the parameters for open (2), specifically those related to
enabling write mode for the new file.  And the write (3) method of an
open file.

(1)
http://docs.python.org/library/stdtypes.html?highlight=replace#str.replace
(2) http://docs.python.org/library/functions.html#open
(3) http://docs.python.org/library/stdtypes.html?highlight=write#file.write

You're almost there it seems.

HTH,

Emile


> 
> 
> I don't know what kind of translated output he need. I guess:
> 
> 1. the name of the file containing the translated output is *
> storyAmer.txt* and it is to located in a subdirectory off your cset1100py
> *assign19*, that is *./cset1100py/assign19/storyAmer.txt* directory named
> 
> 
> What kind of translated output do you want?
> 
> (1) A list of wrong words and a list of right words, like this:
> 
>  Wrong words in the text are: ..
> 
>   Right words should be: ..
> 
> 
> 
> OR
> 
> 
> 
> (2) The content of the text but has already been translated, like this:
> 
> 
> 
> I am really glad that I took CSET 1100.
> We get to *analyze* all sorts of real-world problems.
> We also have to *memorize* some programming language syntax.
> But, the *center* of our focus is game programming and it is fun.
> Our instructor adds *color* to his lectures that make them interesting.
> It is an honour to be part of this class!
> 
> 
> 
> 在 2010年3月28日 下午12:26,Shurui Liu (Aaron Liu)写道:
> 
>> Since English is not my native language, so I got confused by some
>> requirement of my assignment. I already done, just want to make sure what I
>> did is what the assignment required, thank you!
>>
>> BTW, I don't know how to do this:
>> If I want to fix some wrong words in a text file, how can I print out the
>> right/fixed text file? Like this:
>> My favor colour is blue. → My favourite color is blue. (Just print out the
>> right thing directly)
>>
>> Thank you!
>>
>> assignment:
>>
>> 1 Write a Python program named british2american.py
>>   that reads the contents of a text file, looks for occurances of uniquely 
>> British spelling, and translates the occurances into the acceptes American 
>> spelling.
>>
>> 1
>> Specifically, you will be looking for the following words: colour, analyse, 
>> memorise, centre and recognise. If found, they are to be
>> replaced with color, analyze, memorize, center and recognize.
>>
>> 1 The following is needed for you to write your program:
>>
>> 1 the name of the file containing the text to be translated is
>> storyBrit.txt
>>   and it is to be located in your cset1100py directory. Copy it from this
>> link
>>   to the designated location.
>>
>> 1 your program, british2american.py, should be located in your cset1100py
>>   directory on et791
>>
>> 1 the name of the file containing the translated output is storyAmer.txt
>>   and it is to located in a subdirectory off your cset1100py directory named
>> assign19, that is ./cset1100py/assign19/storyAmer.txt
>>
>> 1 the original file, storyBrit.txt, should be left unchanges
>> This is british2american.py
>> # Translate wrong British words
>> #Create an empty file
>> print "\nReading characters from the file."
>> raw_input("Press enter then we can move on:")
>> text_file = open("storyBrit.txt", "r+")
>> whole_thing = text_file.read()
>> print whole_thing
>> raw_input("Press enter then we can move on:")
>> print "\nWe are gonna find out the wrong British words."
>> # Press enter and change the wrong words
>> if "colour" in whole_thing:
>>  print "The wrong word is 'colour' and the right word is 'color'"
>> if "analyse" in whole_thing:
>>  print "the wrong word is 'analyse' and the right word is 'analyze'"
>> if "memorise" in whole_thing:
>>  print "the wrong word is 'memorise' and the right word is 'memorize'"
>> if "centre" in whole_thing:
>>  print "the wrong word is 'centre' and the right word is 'center'"
>> if "recognise" in whole_thing:
>>  print "the wrong word is 'recognise' and the right word is 'recognize'"
>> if "honour" in whole_thing:
>>  print "the wrong word is 'honour' and the right word is 'honor'"
>> # We are gonna save the right answer to storyAmer.txt
>> w = open('storyAmer.txt', 'w')
>> w.write('I am really glad that I took CSET 1100.')
>> w.write('\n')
>> w.write('We get to analyse all sorts of real-world problems.\n')
>> w.write('\n')
>> w.write('We also have to memorize some programming language syntax.')
>> w.

Re: [Tutor] ask

2010-03-28 Thread Shurui Liu (Aaron Liu)
I came out with a transigent answer: save the right text file*(storyAmer.txt
*) at the right place /cset1100py/assign19/
storyAmer.txt. Then I just add a command after the command which picked out
wrong words.

I wanna add
text_file = open("storyAmer.txt", "r")
But I don't know how to add its path in parentheses.

What do u think?


2010/3/28 Shurui Liu (Aaron Liu) 

> I came out with a transigent answer: save the right text file*
> (storyAmer.txt*) at the right place /cset1100py/assign19/storyAmer.txt.
> Then I just add a command after the command which picked out wrong words.
>
> I wanna add
> text_file = open("storyAmer.txt", "r")
> But I don't know how to add its path in parentheses.
>
> What do u think?
>
> 2010/3/28 C M Caine 
>
> 2010/3/28 Shurui Liu (Aaron Liu) :
>> > You know what, I just don't understand this line:
>> >
>> the name of the file containing the translated output is storyAmer.txt and 
>> it is to located.
>> >
>> > I don't know what kind of translated output he need. I guess:
>> >
>> > the name of the file containing the translated output is storyAmer.txt
>> and
>> > it is to located in a subdirectory off your cset1100pyassign19, that is
>> > ./cset1100py/assign19/storyAmer.txt directory named
>> >
>> > What kind of translated output do you want?
>> >
>> > (1) A list of wrong words and a list of right words, like this:
>> >
>> > Wrong words in the text are: ..
>> >
>> >  Right words should be: ..
>> >
>> >
>> >
>> > OR
>> >
>> >
>> >
>> > (2) The content of the text but has already been translated, like this:
>>
>> I think he wants (2).
>>
>> (1) is a fairly trivial task and involves no real processing.
>>
>
>
>
> --
> Shurui Liu (Aaron Liu)
> Computer Science & Engineering Technology
> University of Toledo
>



-- 
Shurui Liu (Aaron Liu)
Computer Science & Engineering Technology
University of Toledo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inter-module global variable

2010-03-28 Thread bob gailer

On 3/28/2010 5:31 AM, spir ☣ wrote:

Hello,

I have a main module importing other modules and defining a top-level variable, 
call it 'w' [1]. I naively thought that the code from an imported module, when 
called from main, would know about w, but I have name errors. The initial trial 
looks as follows (this is just a sketch, the original is too big and 
complicated):

# imported "code" module
__all__ = ["NameLookup", "Literal", "Assignment", ...]

# main module
from parser import parser
from code import *
from scope import Scope, World
w = World()

This pattern failed as said above. So, I tried to "export" w:

   
I have read the above several times. I do not comprehend your problem. 
Perhaps someone else will. If not please try to explain it in a 
different way. ALWAYS post the traceback.



# imported "code" module
__all__ = ["NameLookup", "Literal", "Assignment", ...]

# main module
from parser import parser
from scope import Scope, World
w = World()
import code #new
code.w = w  ### "export"
from code import *

And this works. I had the impression that the alteration of the "code" module object would not 
propagate to objects imported from "code". But it works. But I find this terribly unclear, fragile, 
and dangerous, for any reason. (I find this "dark", in fact ;-)
Would someone try to explain what actually happens in such case?
Also, why is a global variable not actually global, but in fact only "locally" 
global (at the module level)?
It's the first time I meet such an issue. What's wrong in my design to raise 
such a problem, if any?

My view is a follow: From the transparency point of view (like for function transparency), the 
classes in "code" should _receive_ as general parameter a pointer to 'w', before they do 
anything. In other words, the whole "code" module is like a python code chunk 
parameterized with w. If it would be a program, it would get w as command-line parameter, or from 
the user, or from a config file.
Then, all instanciations should be done using this pointer to w. Meaning, as a 
consequence, all code objects should hold a reference to 'w'. This could be 
made as follows:

# main module
import code
code.Code.w = w
from code import *

# "code" module
class Code(object):
 w = None   ### to be exported from importing module
 def __init__(self, w=Code.w):
 # the param allows having a different w eg for testing
 self.w = w
# for each kind of code things
class CodeThing(Code):
 def __init__(self, args):
 Code.__init__(self)
 ... use args ...
def do(self, args):
... use args and self.w ...

But the '###' line looks like  an ugly trick to me. (Not the fact that it's a 
class attribute; as a contrary, I often use them eg for config, and find them a 
nice tool for clarity.) The issue is that Code.w has to be exported.
Also, this scheme is heavy (all these pointers in every living object.) 
Actually, code objects could read Code.w directly but this does not change much 
(and I lose transparency).
It's hard for me to be lucid on this topic. Is there a pythonic way?


Denis

[1] The app is a kind of interpreter for a custom language. Imported modules 
define classes for  objects representing elements of code (literal, assignment, 
...). Such objects are instanciated from parse tree nodes (conceptually, they 
*are* code nodes). 'w' is a kind of global scope -- say the state of the 
running program. Indeed, most code objects need to read/write in w.
Any comments on this model welcome. I have few knowledge on implementation of 
languages.


vit esse estrany ☣

spir.wikidot.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
   



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

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Introduction to modelling with Python

2010-03-28 Thread Eike Welk
On Sunday March 28 2010 19:37:41 AG wrote:
> Now that's looking very much along the lines of what I had in mind
> Eike.  Very pricey ... might have to sit on that one for a while and
> scout around for a used copy.  I can certainly use the on-line resource
> for as many pages as it allows one to access until I either find a
> cheaper version or perhaps win a lottery!!
Maybe you can get it as an inter library loan. Buying it is unnecessary; once 
you have some knowledge of the tools, you get everywhere you want with the 
online documentation and some questions in the relevant mailing lists. 


As an alternative you could try the online documentation at the Scipy website. 
Numpy and Scipy are the basic libraries for numerical computation with Python. 
The material at the website is not as good as the Langtangen book, and it 
covers far fewer different subjects, but it might be good enough to get you 
started.

First read the "Getting Started" section. Then look at the "Cookbook" articles 
and study some that are relevant for you.   
http://www.scipy.org/

Additionally subscribe to the Numpy/Scipy mailing lists. You could ask 
questions how to solve specific problems. The people there are usually very 
helpful. 

> 
> But, yep, this looks like what I had in mind - so anything else like
> this would be good as well.

I'm very glad that I could be helpful. 


Eike.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Introduction to modelling with Python

2010-03-28 Thread AG

Eike Welk wrote:

On Sunday March 28 2010 19:37:41 AG wrote:
  

Now that's looking very much along the lines of what I had in mind
Eike.  Very pricey ... might have to sit on that one for a while and
scout around for a used copy.  I can certainly use the on-line resource
for as many pages as it allows one to access until I either find a
cheaper version or perhaps win a lottery!!

Maybe you can get it as an inter library loan. Buying it is unnecessary; once 
you have some knowledge of the tools, you get everywhere you want with the 
online documentation and some questions in the relevant mailing lists. 

  


The idea of an inter-library loan is a sound one.  I hadn't thought of 
that, so will give that a try.


As an alternative you could try the online documentation at the Scipy website. 
Numpy and Scipy are the basic libraries for numerical computation with Python. 
The material at the website is not as good as the Langtangen book, and it 
covers far fewer different subjects, but it might be good enough to get you 
started.


  


I've just begun with numpy and matlibplot (pyplot), so these are good 
suggestions.


First read the "Getting Started" section. Then look at the "Cookbook" articles 
and study some that are relevant for you.   
http://www.scipy.org/


  


Thanks.  These are leads worth following up on.
Additionally subscribe to the Numpy/Scipy mailing lists. You could ask 
questions how to solve specific problems. The people there are usually very 
helpful. 

  

But, yep, this looks like what I had in mind - so anything else like
this would be good as well.



I'm very glad that I could be helpful. 



Eike.
  


Thank you again.

AG
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] how to change some words in a text file

2010-03-28 Thread Shurui Liu (Aaron Liu)
Here's the thing, I wanna change some wrong words from a text file like this:

"I am a studaet." -> "I am a student."

I have tried to use this command:
str = "I am a studaet."
newstr = str[0:8] + "ent"
print newstr


But the system said TypeError: 'type' object is unsubscriptable

What's wrong?

-- 
Shurui Liu (Aaron Liu)
Computer Science & Engineering Technology
University of Toledo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to change some words in a text file

2010-03-28 Thread Emile van Sebille

On 3/28/2010 2:23 PM Shurui Liu (Aaron Liu) said...

Here's the thing, I wanna change some wrong words from a text file like this:

"I am a studaet." ->  "I am a student."

I have tried to use this command:
str = "I am a studaet."
newstr = str[0:8] + "ent"
print newstr


But the system said TypeError: 'type' object is unsubscriptable

What's wrong?

str is an unfortunate variable name choice -- try oldstr instead.  What 
you've done is often called shadowing.  I don't get the error here, but 
I'm guessing that's because I'm on 2.6 and you're on 3.x?


Emile

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to change some words in a text file

2010-03-28 Thread Shashwat Anand
>>> s = "I am a studaet."
>>> new_s = s[0:8] + 'ent'
>>> print new_s
I am a sent

You are using str as a variable, str is used to convert anything into string

>>> a  = 0
>>> b = str(a)
>>> type(b)



On Mon, Mar 29, 2010 at 2:53 AM, Shurui Liu (Aaron Liu)
wrote:

> Here's the thing, I wanna change some wrong words from a text file like
> this:
>
> "I am a studaet." -> "I am a student."
>
> I have tried to use this command:
> str = "I am a studaet."
> newstr = str[0:8] + "ent"
> print newstr
>
>
> But the system said TypeError: 'type' object is unsubscriptable
>
> What's wrong?
>
> --
> Shurui Liu (Aaron Liu)
> Computer Science & Engineering Technology
> University of Toledo
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Introduction to modelling with Python

2010-03-28 Thread Eike Welk
Also bookmark this page, it will be very useful once you have a little 
knowledge about Numpy:
http://www.scipy.org/Numpy_Example_List_With_Doc

This is the page that I use most often. 


Eike.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to change some words in a text file

2010-03-28 Thread Shurui Liu (Aaron Liu)
Tell me how to do what i want, please.

2010/3/28 Shashwat Anand :
 s = "I am a studaet."
 new_s = s[0:8] + 'ent'
 print new_s
> I am a sent
>
> You are using str as a variable, str is used to convert anything into string
>
 a  = 0
 b = str(a)
 type(b)
> 
>
>
> On Mon, Mar 29, 2010 at 2:53 AM, Shurui Liu (Aaron Liu) 
> wrote:
>>
>> Here's the thing, I wanna change some wrong words from a text file like
>> this:
>>
>> "I am a studaet." -> "I am a student."
>>
>> I have tried to use this command:
>> str = "I am a studaet."
>> newstr = str[0:8] + "ent"
>> print newstr
>>
>>
>> But the system said     TypeError: 'type' object is unsubscriptable
>>
>> What's wrong?
>>
>> --
>> Shurui Liu (Aaron Liu)
>> Computer Science & Engineering Technology
>> University of Toledo
>> ___
>> Tutor maillist  -  tu...@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Shurui Liu (Aaron Liu)
Computer Science & Engineering Technology
University of Toledo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] bind line-oriented device output?

2010-03-28 Thread Tom Roche

I'd like to learn to pythonically redirect the output from a
line-oriented character device to a particular file or process,
regardless of focus, on a generic graphical OS. But I don't want to
redirect stdin entirely. Here's the usecase:

My school has a seminar for which we record attendance by scanning the
student ID card, or rather the barcode on its back, with a handheld
USB scanner. This is pretty straightforward, except that the barcode
scanner is like a keyboard writing the ASCII equivalent of the barcode
(== the student's ID#) to stdin. FWIW, the scanner writes lines: I'm
not sure if EOL is \r, \n, or \r\n, but I suspect the latter.

Since the scanner is connected to an ordinary multiprocessing laptop on
which one will likely be doing other things while scanning (notably
setting up to record the presenter), it sometimes happens (especially
until one learns to pay attention to this) that one writes to a frame
other than the text file into which we want record attendee ID#s. This
semester recurs every {fall, spring}, so someone faces this {pitfall,
learning curve} at regular intervals.

How to prevent writing the wrong target? One trivial solution--shlep a
dedicated USB host for the scanner--is deprecated. An OS-specific
solution (e.g. relying on a linux raw device) is also undesirable: I
use ubuntu, but others will probably use mac or windows.

Rather, It Would Be Nice, and useful for this seminar's mechanics, to
be able to run some code to which one could say, see this device? and
this file? Make the device's output go only to that file. For extra
credit, don't let anything else write that file while this code is
running.

Can python do that? Or does one need to get closer to the metal?

TIA, Tom Roche 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to change some words in a text file

2010-03-28 Thread Walter Prins
On 28 March 2010 23:37, Shurui Liu (Aaron Liu)  wrote:

> Tell me how to do what i want, please.
>

Both me and someone else have already told you how to replace a substring in
a string with something else in your earlier question/posting/thread.  If
you've not understood what was written there, then please ask again and
specify what specifically you're having difficulty with.  If however you've
not yet looked into/tried out what we've suggested, then please do try that
first, and then come back if you have problems.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] commands

2010-03-28 Thread Shurui Liu (Aaron Liu)
# Translate wrong British words

#Create an empty file
print "\nReading characters from the file."
raw_input("Press enter then we can move on:")
text_file = open("storyBrit.txt", "r+")
whole_thing = text_file.read()
print whole_thing
raw_input("Press enter then we can move on:")
print "\nWe are gonna find out the wrong British words."
corrections = {'colour':'color', 'analyse':'analyze',
'memorise':'memorize', 'centre':'center', 'recognise':'recognize',
'honour':'honor'}
texto = whole_thing
for a in corrections:
texto = texto.replace(a, corrections[a])
print texto

# Press enter and change the wrong words
if "colour" in whole_thing:
print "The wrong word is 'colour' and the right word is 'color'"
if "analyse" in whole_thing:
print "the wrong word is 'analyse' and the right word is 'analyze'"
if "memorise" in whole_thing:
print "the wrong word is 'memorise' and the right word is 'memorize'"
if "centre" in whole_thing:
print "the wrong word is 'centre' and the right word is 'center'"
if "recognise" in whole_thing:
print "the wrong word is 'recognise' and the right word is 'recognize'"
if "honour" in whole_thing:
print "the wrong word is 'honour' and the right word is 'honor'"

# We are gonna save the right answer to storyAmer.txt
w = open('storyAmer.txt', 'w')
w.write('I am really glad that I took CSET 1100.')
w.write('\n')
w.write('We get to analyse all sorts of real-world problems.\n')
w.write('\n')
w.write('We also have to memorize some programming language syntax.')
w.write('\n')
w.write('But, the center of our focus is game programming and it is fun.')
w.write('\n')
w.write('Our instructor adds color to his lectures that make them interesting.')
w.write('\n')
w.write('It is an honor to be part of this class!')
w = open("assign19/storyAmer.txt", "w")

w.close()



This is what I have done, I don't understand why this program cannot
fix "analyse".

-- 
Shurui Liu (Aaron Liu)
Computer Science & Engineering Technology
University of Toledo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inter-module global variable

2010-03-28 Thread Dave Angel

spir # wrote:

On Sun, 28 Mar 2010 21:50:46 +1100
Steven D'Aprano  wrote:

  

On Sun, 28 Mar 2010 08:31:57 pm spir ☣ wrote:


I'm going to assume you really want a single global value, and that you 
won't regret that assumption later.


We talked at length about how to access that global from everywhere that 
cares, and my favorite way is with a globals module. And it should be 
assigned something like:


globals.py:
class SomeClass (object):
def

def init(parameters):
global world
world = SomeClass(parameters, moreparamaters)

Then main can do the following:
import globals
globals.init(argv-stuff)

And other modules can then do
import globals.world as world

And they'll all see the same world variable. Nobody should have their 
own, but just import it if needed.



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] commands

2010-03-28 Thread Dave Angel

Shurui Liu (Aaron Liu) wrote:

# Translate wrong British words

#Create an empty file
print "\nReading characters from the file."
raw_input("Press enter then we can move on:")
text_file = open("storyBrit.txt", "r+")
whole_thing = text_file.read()
print whole_thing
raw_input("Press enter then we can move on:")
print "\nWe are gonna find out the wrong British words."
corrections = {'colour':'color', 'analyse':'analyze',
'memorise':'memorize', 'centre':'center', 'recognise':'recognize',
'honour':'honor'}
texto = whole_thing
for a in corrections:
texto = texto.replace(a, corrections[a])
print texto

# Press enter and change the wrong words
if "colour" in whole_thing:
print "The wrong word is 'colour' and the right word is 'color'"
if "analyse" in whole_thing:
print "the wrong word is 'analyse' and the right word is 'analyze'"
if "memorise" in whole_thing:
print "the wrong word is 'memorise' and the right word is 'memorize'"
if "centre" in whole_thing:
print "the wrong word is 'centre' and the right word is 'center'"
if "recognise" in whole_thing:
print "the wrong word is 'recognise' and the right word is 'recognize'"
if "honour" in whole_thing:
print "the wrong word is 'honour' and the right word is 'honor'"

# We are gonna save the right answer to storyAmer.txt
w = open('storyAmer.txt', 'w')
w.write('I am really glad that I took CSET 1100.')
w.write('\n')
w.write('We get to analyse all sorts of real-world problems.\n')
w.write('\n')
w.write('We also have to memorize some programming language syntax.')
w.write('\n')
w.write('But, the center of our focus is game programming and it is fun.')
w.write('\n')
w.write('Our instructor adds color to his lectures that make them interesting.')
w.write('\n')
w.write('It is an honor to be part of this class!')
w = open("assign19/storyAmer.txt", "w")

w.close()



This is what I have done, I don't understand why this program cannot
fix "analyse".

  
You do some work in texto, and never write it to the output file.  
Instead you write stuff you hard-coded in literal strings in your program.


And you never fixed the mode field of the first open() function, as 
someone hinted at you.   And you don't specify the output file location, 
but just assume it's in the current directory.  For that matter, your 
open of the input file assumes it's in the current directory as well.  
But your assignment specified where both files would/should be.



DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor