Re: [Tutor] a puzzle about -3**2 vs (-3)**2

2015-07-31 Thread Jose Amoreira

On 07/31/2015 11:36 AM, Alan Gauld wrote:

On 31/07/15 10:55, Jose Amoreira wrote:


Given the precedence rules already mentioned by Alan and Todd, the
results of the operations you showed us are exactly as expected. You'll
get the same results if you try with a pocket calculator or using any
other programming language or scientific package.


The point I was making is that you may NOT get the same results in any
other language. Each language designer is free to define his/her own
precedence rules. Most try to follow the rules of math, but some do not
(like Lisp using prefix notation rather than infix). Several languages
evaluate purely left to right, at least 1 goes from right to left.

In programming you have to learn the  language and not expect it to
conform to any preconceived ideas of how it *should* work.



Yes, you are right, Alan. That expectation is often the source of much 
frustration when learning a new language.
But, for this particular application, this particular language even 
conforms to those general preconceived ideas... And I'm glad it does!


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


Re: [Tutor] a puzzle about -3**2 vs (-3)**2

2015-07-31 Thread Jose Amoreira

Hello!
On 07/31/2015 01:58 AM, D Wyatt wrote:

I just read in a book a little while ago that ** trumps a negative
sign?  I am struggling with the audacity of that as -1 is negative 1,
NOT minus 1.


I'm not sure about what you mean by "trumps", but the square of negative 
one is positive one (negative times negative gives positive).



How can an arithmetic operation trump an attribute of a
negative integer?  It truly makes no sense to me.  Thank you for any
enlightenment you can provide.

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

3**2

9

(-3)**2

9

-3**2

-9






Given the precedence rules already mentioned by Alan and Todd, the 
results of the operations you showed us are exactly as expected. You'll 
get the same results if you try with a pocket calculator or using any 
other programming language or scientific package. Or MS-excel.


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


Re: [Tutor] Surprising behaviour of optional argument

2014-07-17 Thread Jose Amoreira

Hi
On 07/17/2014 06:34 PM, Danny Yoo wrote:





Yeah; the default value is not reevaluated between calls.  It's a common
gotcha.  Here are a few links to read more:

http://effbot.org/zone/default-values.htm

http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments

Good luck!



Aha, the object that stores the default value for the optional argument 
is created at the time of the execution of the function definition and 
mutable objects do mutate, so that's that. It makes a lot of sense.

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


[Tutor] Surprising behaviour of optional argument

2014-07-17 Thread Jose Amoreira

Hello
I stumbled on something I found surprising. I'm using standard python 
(cpython, I guess) 2.7 on openSuse 13.1.


Consider the function

In [2]: def f(x,y=[]):
   ...: print y
   ...: y.append(x)
   ...: return x

This is the output of repeated calls to this function:

In [3]: f(1)
[]
Out[3]: 1
In [4]: f(2)
[1]
Out[4]: 2
In [5]: f(3)
[1, 2]
Out[5]: 3

So, the function seems to keep the value of the optional argument y over 
repeated calls. I was expecting that the optional argument, if not set 
explicitly in the calling command, would always assume the default value 
(the empty list), at every call.


I guess it has something to do with the mutability of the optional 
argument (in this case, a list), because it works as I expect if the 
optional argument is an int, for instance:


In [8]: def g(x,y=0):
   ...: print y
   ...: y += x
   ...: return x
   ...:

In [9]: g(1)
0
Out[9]: 1
In [10]: g(2)
0
Out[10]: 2

(No memory of previous calls to the function.)
Is there a rationale for this behavior?
Thanks for any help,
Ze
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about style

2014-07-17 Thread Jose Amoreira

Hello,

On 07/17/2014 12:05 AM, Alan Gauld wrote:


Just throwing this idea in without really thinking about it...
Would itertools.groupby work?

It takes a sorted collection and groups the items found based on a key
function. If the key function deemed two items identical if they were
within distance X of each other then groupby might help.

The itertools functions are generally space efficient and
therefore good for large volumes of data.



Thanks for the suggestion, I didn't know about groupby. I gave it a try. 
The key function argument is optional; if we don't supply one, grouby 
groups *equal* list elements. But I want to group *close enough* 
elements (close enough meaning that their distance is less than some 
reference value), and I didn't manage to specify a key function in a 
form suitable for use with groubpy. I should spend some more time 
studying the examples.


Anyway, thanks a lot, it's always good to know a new module in the 
standard library.


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


Re: [Tutor] Question about style

2014-07-16 Thread Jose Amoreira

Hi!

On 07/16/2014 10:14 PM, Wolfgang Maier wrote:


careful here: you just stored a tuple instead of a list; doesn't matter
for your current implementation, but may bite you at some point.


Oh, you're right. Silly mistake, even if harmless for the application I 
have in mind.



 else:
 # x does not belong to any cluster, create a new one
 clusters.append([x,1])
 # return list with centers
 return [center for center, _ in clusters]



Your building of the close_to list with Trues and Falses, then using it
to find the original element again makes me think that you're a regular
R user ? Using such a logical vector (I guess that's what you'd call it
in R) should (almost) never be required in Python.


No, I use mainly python and fortran (but I'm not a "real" programmer). I 
arrived at this particular function from a previous version which only 
took one single line and was quite readable, but it didn't compute the 
centers of the clusters; the first value added to a new cluster would be 
the cluster value, regardless of other added values. Then I decided that 
I wanted the centroids of each cluster and this was the result. It 
smelled bad, but I was trying to hang on to my (supposedly) smart one 
liner...



Here's an implementation of this idea demonstrating how, in Python, you
typically use the builtin enumerate function to avoid "logical vectors"
or other kinds of index juggling:

def aglomerate(x_lst, delta=1.e-5):
 centers = []
 sizes = []
 for x in x_lst:
 for i, center in enumerate(centers):
 if abs(x - center) < delta:
 # x is close to a cluster
 #update the cluster center including the new value,
 #and increment dimension of cluster
 n = sizes[i]
 centers[i] = (n * center + x)/(n+1)
 sizes[i] = n+1
 break
 else:
 # this block is executed only when the break in the preceeding
 # block wasn't reached =>
 # x does not belong to any cluster, create a new one
 centers.append(x)
 sizes.append(1)
 # return list with centers
 return centers


Thanks, Wolfgang. You were very helpful.

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


[Tutor] Question about style

2014-07-16 Thread Jose Amoreira

Hello
I wrote a function that, given a list of numbers, finds clusters of 
values by proximity and returns a reduced list containing the centers of 
these clusters. However, I find it rather unclear. I would appreciate 
any comments on how pythonic my function is and suggestions to improve 
its readability.

The function is:

def aglomerate(x_lst, delta=1.e-5):
clusters = [] #list of pairs [center, number of clustered values]
for x in x_lst:
close_to = [abs(x - y) < delta for y,_ in clusters]
if any(close_to):
# x is close to a cluster
index = close_to.index(True)
center, n = clusters[index]
#update the cluster center including the new value,
#and increment dimension of cluster
clusters[index] = (n * center + x)/(n+1), n+1
else:
# x does not belong to any cluster, create a new one
clusters.append([x,1])
# return list with centers
return [center for center, _ in clusters]

Examples:
1. No clusters in x_lst:
In [52]: aglomerate([1., 2., 3., 4.])
Out[52]: [1.0, 2.0, 3.0, 4.0]

2. Some elements in x_lst are equal:
In [53]: aglomerate([1., 2., 1., 3.])
Out[53]: [1.0, 2.0, 3.0]

3. Some elements in x_lst should be clustered:
In [54]: aglomerate([1., 2., 1.1, 3.], delta=0.2)
Out[54]: [1.05, 2.0, 3.0]

So, the function seems to work as it should, but can it be made more 
readable?


Thanks for any help.
Ze
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Slices of lists of lists

2014-03-28 Thread Jose Amoreira

On 03/28/2014 10:32 AM, Alan Gauld wrote:


No, standard slices on the first element will give you sublists of the
first row. Python doesn't have any concept of that second dimension, it
only sees a list of items. The fact those items are themselves lists is
purely incidental to the interpreter.


HTH


Thanks, Alan. It was very helpful. I see it now:
l[:] is just a copy of the list itself. Then, l[:][k] == l[k].
Thanks again.
Jose
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Slices of lists of lists

2014-03-28 Thread Jose Amoreira




Jose,

Just for clarity, are you trying to access a particular *column* in your
last example?

Bob

Yes, that's it! I wanted to say "column", not "row" in my last example. 
Sorry about that! Thanks

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


[Tutor] Slices of lists of lists

2014-03-28 Thread Jose Amoreira

Hello!
Here is something that surprised me and I still didn't get it.

If we want to store a matrix in pure python (no numpy), the first thing 
that comes to (my) mind is to use a list of lists, like the list l below:

In [1]: l=[
   ...:[11,12,13],
   ...:[21,22,23]
   ...:   ]

We can access individual components of this object in a simple, to be 
expected way:


In [2]: l[0][1], l[1][0]
Out[2]: (12, 21)

OK, that's fine. If we want to access individual rows of this matrix 
like object, the standard slice notation (on the second index) works as 
expected also:


In [3]: l[0][:]
Out[3]: [11, 12, 13]

In [4]: l[1][:]
Out[4]: [21, 22, 23]

Again, fine! But what if we want to access a particular row? My first 
guess was that standard slice notation on the first index would do it, 
but it doesn't! Instead, we get the rows again:


In [6]: l[:][0]
Out[6]: [11, 12, 13]

In [7]: l[:][1]
Out[7]: [21, 22, 23]

Why is this so?
Thanks,
Jose Amoreira
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of references to object properties

2013-01-19 Thread Jose Amoreira
Thanks for the explanation, Alan
> 
> Is there a good reason to want to do such a thing?

There is a reason, but maybe you won't consider it a good one... 
I was writing a small program to simulate the gravitational dynamics of a 
system of many planets, using scipy's odeint to solve the equations of motion. 
I defined a class, CelestialBody, that describes objects that represent 
planets in my simulation. These objects have three attributes: position, 
velocity and mass (the first two are 3D-vectors; as such, the number of 
attributes is actually 7). The many-body system is represented in the 
simulation by a list of CelestialBody objects.

The dynamical state of the system is represented by a 6N (N being the number 
of planets) component array storing the components of the position and linear 
momentum of each body, and the integration procedures (odeint in this case) 
usually take this array as argument. 

So, in my simulation code I have a list of planets (objects of class 
CelestialBody) because it is a natural way of representing the systems I want 
to simulate, and another list (an numpy.array, actually) storing the positions 
and momenta of each planet, needed for the numerical processing of the 
simulation. But the positions and momenta are already present in the planet 
list, since the objects themselves store that information. Then, the second 
list, even if necessary, is a duplication of things that already are defined 
in the code. I don't like it. It'd be better (no duplication) if it was just a 
list of references to the values stored in the planet objects, I think.

But I see your point.

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


Re: [Tutor] list of references to object properties

2013-01-18 Thread Jose Amoreira
Thanks, Peter.
I was trying to avoid the regenerate step for updating. But maybe I can
restructure my code and objects to make this simpler. Before that I'll try
this view approach.
Thanks again
Ze


On Fri, Jan 18, 2013 at 11:37 AM, Peter Otten <__pete...@web.de> wrote:

> Jose Amoreira wrote:
>
> > Hello
> > Suppose I have a list l_obj of similar objects. Is there any way I can
> > generate a list l_prp of references to a given property of those objects
> > in such a way that, if change the value of one element in l_prp, the
> > corresponding object in l_obj gets its property updated, and vice-versa?
> > Let give an example of what I have in mind.
> >
> > In [1]: class MyCls(object):
> >
> >...: def __init__(self,a):
> >
> >...: self.prp = a
> >
> >...:
> >
> > In [2]: l_obj = [MyCls(float(i)) for i in range(3)]
> >
> > In [3]: l_prp = [item.prp for item in l_obj]
> >
> > In [4]: for ob in l_obj:
> >
> >...: print ob.prp,
> >
> >...:
> >
> > 0.0 1.0 2.0
> >
> > In [5]: l_prp
> >
> > Out[5]: [0.0, 1.0, 2.0]
> >
> > In [6]: l_prp[1]=5.
> >
> > In [7]: l_obj[1].prp
> >
> > Out[7]: 1.0
> >
> > As expected, changes in l_prp do not change the properties of the
> elements
> > in l_obj, neither do changes in l_obj's element's properties change the
> > values in l_prp.
> >
> > Is there a simple way to implement such connections?
>
> No. You'd need something like the observer pattern (listeners in Java),
> where the class owning the property (MyCls) has to cooperate. The
> administrative overhead is relatively high.
>
> The pythonic way is to regenerate the l_prp list every time you need an up-
> to-date overview of the current values.
>
> An intermediate approach is to turn l_prp into a view on the l_obj list:
>
> from collections import Sequence
>
> class A(object):
> def __init__(self, attrib):
> self.attrib = attrib
>
> class AttribView(Sequence):
> def __init__(self, items):
> self._items = items
> def __getitem__(self, index):
> return self._items[index].attrib
> def __len__(self):
> return len(self._items)
> def __repr__(self):
> return repr(list(self))
>
> items = [A(c) for c in "abcde"]
> attribs = AttribView(items)
> print attribs
> items[1].attrib = 42
> print attribs
>
>
> ___
> 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] list of references to object properties

2013-01-18 Thread Jose Amoreira
Hello
Suppose I have a list l_obj of similar objects. Is there any way I can
generate a list l_prp of references to a given property of those objects in
such a way that, if change the value of one element in l_prp, the
corresponding object in l_obj gets its property updated, and vice-versa?
Let give an example of what I have in mind.

In [1]: class MyCls(object):

   ...: def __init__(self,a):

   ...: self.prp = a

   ...:

In [2]: l_obj = [MyCls(float(i)) for i in range(3)]

In [3]: l_prp = [item.prp for item in l_obj]

In [4]: for ob in l_obj:

   ...: print ob.prp,

   ...:

0.0 1.0 2.0

In [5]: l_prp

Out[5]: [0.0, 1.0, 2.0]

In [6]: l_prp[1]=5.

In [7]: l_obj[1].prp

Out[7]: 1.0

As expected, changes in l_prp do not change the properties of the elements
in l_obj, neither do changes in l_obj's element's properties change the
values in l_prp.

Is there a simple way to implement such connections?

Thanks,

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


Re: [Tutor] Where to put small auxiliary function

2012-07-20 Thread Jose Amoreira
Hi Mark,
Thanks.

> [SNIP]
>> Let me give an example:
>>
>> def is_odd(k):
>>  if k % 2 == 0:
>>  return False
>>  else:
>>  return True
>
>
> I'll point out before anyone else does that you can write this function as a
> one line return.  I'll leave you to work out how.  Personally I prefer the
> longer version but each to their own.
>

OK, but if I wrote it as an one-liner, then it wouldn't be much use as
an example for my question...

>[SNIP]
> Don't put it in the class.  It's a general purpose function that can be used
> anywhere so keep it at the module level.
>

OK, thanks. That was the kind of advice I was hoping for.
Ze
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Where to put small auxiliary function

2012-07-20 Thread Jose Amoreira
Hi.
This is a question about style. I have a class definition that calls a
small auxiliary function. Because this function isn't used anywhere
else, I'd like to include it inside the class definition. However, if
I do that, I'll have to use "self" in the call argument, which is (I
think) rather awkward.
Let me give an example:

def is_odd(k):
if k % 2 == 0:
return False
else:
return True

class MyOddNbr(object):
def __init__(self, k):
if is_odd(k):
self.k = k
else:
self.k = k + 1

This works fine, but I'd like to have is_odd defined inside the class
definition, because that's the only context where that function is
used. That would be something like

class MyOddNbr(object):
def is_odd(self,k):
if k % 2 == 0:
return False
else:
return True
def __init__(self,k):
if self.is_odd(k):
self.k = k
else:
self.k = k + 1

This also works fine, but the function is_odd() is so simple and
generic that I find it strange to define it with is_odd(self,k) or to
call it with is_odd(self,k).
What is the pythonic way of doing this kind of stuff?
Thanks.
Ze
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Solve wave equation

2012-02-24 Thread Jose Amoreira
On Thursday, February 23, 2012 12:57:39 PM David Craig wrote:
> Hi,
> I am trying to write some code that will solve the 2D wave equation by
> the finite difference method, but it just returns an array full of zeros
> and NaN's. Not sure where I am going wrong, the code is attached so if
> could someone point me in the right direction I'd appreciate this.
> Thanks
> D

Let me add my 2 cents to Steven's suggestions.

The main cicle of your program can be reorganized, pulling out all constant 
calculations. Where you write
>for t in range(2,nsteps-1):
>
>
>for z in range(1,nz-1):
>
>for x in range(2,nx-1):
>
>p[xs,zs,t] = s[t]
>
>k = (c*dt/h)**2
>
>p[x,z,t] = 2*p[x,z,t-1] - p[x,z,t-2] + [...]

I'd write

k = (c*dt/h)**2
for t in range(2,nsteps-1):
p[xs,zs,t] = s[t]
for z in range(1,nz-1):
for x in range(2,nx-1):
p[x,z,t] = 2*p[x,z,t-1] - p[x,z,t-2] + [...]

Like that you don't have to compute the value of k (wich is constant) for each 
cell in your mesh and for every time slice. I didn't quite understand the way 
you integrate the source in the calculation, but if it works the way you do 
it, it should also work putting it out of the x and z loops; like that, you 
just have to compute it once for each time slice.

Also, whenever possible, try to implement the iterations (for loops) over 
array elements as whole array operations, wich are way faster then python for 
loops. For instance, the laplacian of the wave function,

>  k*(p[x+1,z,t-1]-4*p[x,z,t-1]+p[x-1,z,t-1]+p[x,z+1,t-1]+p[x,z-1,t-1])

can be computed at once (without for loops) with something like (haven't tryed 
it, take care, read the docs)

>k*(roll(p[:,:,t-1],-1,axis=1) - 4*p[:,:,t-1] + roll(p[:,:,t-1],1,axis=1) +
roll(p[:,:,t-1],-1,axis=0) + roll(p[:,:,t-1],1,axis=0))

(mind the linebreak). This expression returns an array with the dimensions of 
your pressure array p. It may have to be tweaked a bit because of boundary 
behaviour of the roll function.
roll() is a numpy function (must be imported from numpy) that shifts the array 
elements. See 
http://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html
Some examples:

In [1]: from numpy import *

In [2]: m=array([[11,12,13],[21,22,23],[31,32,33]])

In [3]: print m
[[11 12 13]
 [21 22 23]
 [31 32 33]]

In [4]: roll(m,-1,axis=1)
Out[4]: 
array([[12, 13, 11],
   [22, 23, 21],
   [32, 33, 31]])

In [5]: roll(m,1,axis=0)
Out[5]: 
array([[31, 32, 33],
   [11, 12, 13],
   [21, 22, 23]])

Finally, about the plot, I find the matplotlib contour function too slow (it's 
not trivial to compute the contour lines) for animations. I prefer a method 
that directly maps values into colors. Someone in this list suggested pygame's 
surfarray methods, and that's what I've been using.
I hope this helps. Cheers,
Ze
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] two-dimensional color map

2012-02-09 Thread Jose Amoreira
On Thursday, February 09, 2012 10:45:35 AM Nate Lastname wrote:
> Have you considered pygame and its surfarray module?

Thanks, Nate. I haven't, but I will.
Ze___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] two-dimensional color map

2012-02-09 Thread Jose Amoreira
I'm so, so sorry! When editing my script before posting it, I accidently 
deleted a line activating matplotlib interactive mode. The correct listing is 
the one below.

Hello
I'm trying to plot a false-color map of a two dimensional function. My main 
problem is that the function I want to plot depends also on time, and I wish 
to show the plot as the function evolves, in real time. My first (and only, so 
far) idea on how to achieve this was to iterate the computation and the plot 
of the values of the function on a 2-D mesh for different times.

Regarding the plot, I tried some options and the one that came closer to what 
I pretend is based on pylab (numpy and matplotlib, I guess), using the 
matshow() method. However, I found that the display of successive frames takes 
longer and longer. The following simple script shows this behaviour:

from matplotlib.pylab import *

ion()
# Display a random matrix with a specified figure number
for i in range(20):
mymatrix = rand(864,864)
fig = matshow(mymatrix,fignum=0)
draw()
quit = raw_input()  #wait for user input before closing graphics window
-

So my questions are
1. Is matshow() appropriate for what I have in mind?
2. Am I using it correctly?
3. Are there better tools for plotting time-dependent 2D data using python?

Thank you very much
Ze Amoreira___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] two-dimensional color map

2012-02-09 Thread Jose Amoreira
Hello
I'm trying to plot a false-color map of a two dimensional function. My main 
problem is that the function I want to plot depends also on time, and I wish 
to show the plot as the function evolves, in real time. My first (and only, so 
far) idea on how to achieve this was to iterate the computation and the plot 
of the values of the function on a 2-D mesh for different times.

Regarding the plot, I tried some options and the one that came closer to what 
I pretend is based on pylab (numpy and matplotlib, I guess), using the 
matshow() method. However, I found that the display of successive frames takes 
longer and longer. The following simple script shows this behaviour:

from matplotlib.pylab import *

# Display a random matrix with a specified figure number
for i in range(20):
mymatrix = rand(864,864)
fig = matshow(mymatrix,fignum=0)
draw()
quit = raw_input()  #wait for user input before closing graphics window
-

So my questions are
1. Is matshow() appropriate for what I have in mind?
2. Am I using it correctly?
3. Are there better tools for plotting time-dependent 2D data using python?

Thank you very much
Ze Amoreira___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] tkfiledialogs and hidden files

2011-11-08 Thread Jose Amoreira
On Tuesday, November 08, 2011 12:38:19 PM Dave Angel wrote:
> On 11/07/2011 09:45 PM, Jose Amoreira wrote:
> > Hello!
> > Is there any way to configure tkFileDialogs so that they don't display
> > hidden files?
> > Thanks.
> > Ze Amoreira
> 
> I can't help you with tk, but maybe I can help you ask a better question.
> 
> "Hidden files" means a different thing on various operating systems.  In
> Linux, it means a name with a leading period. In Windows, it can mean a
> file with one or more of several attributes.  There's even some
> ambiguity in the latter.
> 
> Please specify (to everyone else, not to me) what environment you're
> targeting in as much detail as possible.

Yes, I'm sorry.
I meant hidden files in Linux.
It's just that my home directory contains a lot of those files and directories 
and I'd rather not need to scroll the dialog display to get to the files/dirs 
that I usually want to select.
Anyway, thank s, Dave.
Ze Amoreira
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] tkfiledialogs and hidden files

2011-11-07 Thread Jose Amoreira
Hello!
Is there any way to configure tkFileDialogs so that they don't display hidden 
files?
Thanks.
Ze Amoreira
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A question about sys.argv

2011-11-01 Thread Jose Amoreira
HiOn Tuesday, November 01, 2011 01:55:18 PM Joel Goldstick wrote:
> On Tue, Nov 1, 2011 at 9:48 AM, Jefferson Ragot  wrote:
> > In a Vista command prompt if I typed this:
> > >>> python  somescript.py  filename
> > 
> > Will sys.argv[1] return a valid path or just the filename?
> > If it just returns the filename, is there a simple way to get the path?
> > 
Here's the contents of my somescript.py:
-
import sys
for index,arg in enumerate(sys.argv):
print index, arg
---

Here is its output:

mu:python$ python somescript.py match.py
0 somescript.py
1 match.py

mu:python$ python somescript.py somescript.py stripaccents.py
0 somescript.py
1 somescript.py
2 stripaccents.py

mu:python$ python somescript.py Hello, how do you do?
0 somescript.py
1 Hello,
2 how
3 do
4 you
5 do?

mu:python$ python somescript.py /home/amoreira/public_html/index.php 
0 somescript.py
1 /home/amoreira/public_html/index.php

mu:python$ python somescript.py /unexistent/directory/unexistent_file.txt
0 somescript.py
1 /unexistent/directory/unexistent_file.txt

So, sys.argv has nothing to do with files or paths, it just stores whatever 
you write in the command line. I don't have a vista system on wich to try 
things, but I'm pretty sure it's the same.
 
> sysargv[1] returns the text following your script.
> 
> You can find the current working directory with this:
> 
> http://docs.python.org/library/os.html#os.getcwd

No. sys.argv[1:] (note the colon) does return (not quite "return", since it's 
not a function call but ok) the text following your script. sys.argv[1] only 
"returns" the *first* word after your script (in the invocation command)

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


[Tutor] How to vectorize a constant function?

2011-02-25 Thread Jose Amoreira
Hello!
In "A Primer on Scientific Programming with Python", they define a vectorized 
function as a scalar function that, when called with a vector argument, 
returns a vector with the values of the function for each of the values stored 
in the argument vector.

I am trying to define a constant vectorized function, that is, one that 
returns 1. (for instance) when called with a scalar argument x and that 
returns array([1.,1.,1.]) when the argument is a three-element array, etc.

Here are a few snippets of an interactive session displaying my failed 
attempts:
---
In [1]: from numpy import *
In [2]: def f(x):
   ...: return 1.
In [3]: x=linspace(0,1,5)
In [4]: print f(x)
--> print(f(x))
1.0
-
That's not what I want, that's a scalar, not a five element array. Next 
option:
-
In [13]: def g(x):
   : return where(True,1.,0.)
In [14]: print g(x)
---> print(g(x))
1.0
---
Still not right. But here is something strange. The values in x are non-
negative, therefore the test x>=0 yelds True for each element in x. One might 
then think that g(x) as defined above would, in this case, be equivalent to 
h(x) defined below:
--
In [16]: def h(x):
   : return where(x>=0,1.,0)
---
However,
---
In [18]: print h(x)
---> print(h(x))
[ 1.  1.  1.  1.  1.]
---
So my questions are:
1. What's the proper way to vectorize a constant function (I know that we 
really don't have to, but I'd like to do it in a first step towards a more 
sophisticated calculation)?
2. Why do g(x) and h(x) return different results?
3. Why doesn't f(x) work?
Thanks
Jose
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] variable numbers of for loops

2010-11-23 Thread Jose Amoreira
On Tuesday, November 23, 2010 02:01:40 pm Mac Ryan wrote:

> The code you wrote generates programs like:
> 
> for l0 in alphabet:
> for l1 in alphabet:
> for l2 in alphabet:
> word = "".join([eval("l"+str(i)) for i in range(n)])
> listOfWords.append(word)
> 
> which are recursive in essence (although the recursion is hard-coded
> rather than dynamic). This is not bad (problems in the domain of
> combinatorics - like yours - get normally solved recursively) but I
> can't imagine what would the advantage of this code over dynamic
> recursion.

I meant recursion in the sense of a function invoking itself (I guess it is 
what you call dynamic recursion). I also can't imagine any advantages of this 
code, I just thought it'd be a fun thing to try.

> 
> As for a more straightforward way to solve your specific problem: I
> would suggest you take a look to the combinatoric generators in the
> itertools module (http://docs.python.org/library/itertools.html).
> 
Thanks for this link, I didn't know about itertools.

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


[Tutor] variable numbers of for loops

2010-11-23 Thread Jose Amoreira
Hi,
This is a somewhat algorithmic question, not strictly pythonic. I was writing 
a program to generate all possible n-letter words with letters taken from an 
alphabet (I mean, if the alphabet is ['a','b'] the one-letter words are 'a' 
and 'b', the two letter words are 'aa', 'ab', 'ba', 'bb' and so on).

I wrote a recursive function that does the job easy enough, but I read 
somewhere that for any recursive algorithm there is a sequential one that is 
equivalent, in the sense that the same output is produced for the same inputs. 
Now the easiest way to solve my n-letter problem sequentially is to, for each 
of the n letters that compose the word, cycle through all the possibilities 
allowed for in the alphabet. However, in this solution the value of n (the 
length of the words) is hardwired, you have to write different programs (with 
different numbers of for loops) for each value of n.

I managed to work around that problem by writing the following function, that 
generates different programs, depending on the value of n,exec's it and 
returns the results:

def allwrds(alphabet,n):
ind = ''
prog = "listOfWords=[]\n"
for i in range(n):
prog += i*ind + 'for l' + str(i) + ' in alphabet:\n'
prog += n*ind + 'word = "".join([eval("l"+str(i)) for i in range(n)])\n'
prog += n*ind + 'listOfWords.append(word)\n'
#print prog   #Uncomment to see the generated program
exec(prog)
return listOfWords

This works fine (comments are welcome, of course) but I find this approach (to 
write programs that write programs that solve the problem) somehow twisted (to 
say the least).

Is there a more straightforward way of solving my specific problem or, better 
yet, a general solution to the need of a variable number of for loops?  
Thanks
Jose
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's the best way to model an unfair coin?

2010-10-24 Thread Jose Amoreira
On Sunday, October 24, 2010 01:18:52 pm Alan Gauld wrote:

> In pseudo code:
> 
> def coinToss(prob = 0.5):
> rand = random()
> if rand >= prob: return True
> else: return False
> 
> print "Heads" if coinToss(6/11) else "Tails"
> 

The only problem with this snippet is integer division: 6/11=0, at least in 
Python 2.6, so that the final line will always print "Heads".

But wait! This is pseudo code! Ah, OK. Then 6/11=0.545454..., and Alan was 
right (as usual).
 
This pseudo code snippet is almost Python code. It looks like Python, it 
smells like Python, it even runs as Python, if you import random from random 
beforehand.
Python really is executable pseudo code!
Cheers
Jose Amoreira
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2010-06-12 Thread Jose Amoreira
On Friday, June 11, 2010 10:12:27 pm Advertising Department wrote:
> #!/Library/Frameworks/Python.framework/Versions/Current/bin/pythonw
> """still thinking in imperative"
> """
> 
> ## obviously this is a bad construct.
> ## Can someone suggest a pythonesque way of doing this?
> 
> 
> def getid():
>   response  = raw_input('prompt')
>   if response not in [ "", "y", "Y", "yes"] :
>   getid() # ouch
>   print "continue working"
>   # do more stuff
>   # do more stuff
> 
> 
> getid()
> dosomething()
> getid()
> dosomethingelse()
> 
> 
> ## obviously this is a bad construct.
> ## Can someone give me a pythonesque way of doing this?
> 
Using recursion for validation, that doesn't sound right. I would rather do it 
with a simple while cycle:

response="any invalid string"
while response not in ["","y","Y","yes"]:
response = raw_input("prompt")

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


Re: [Tutor] Looking for duplicates within a list

2010-06-11 Thread Jose Amoreira
On Friday, June 11, 2010 02:57:34 pm Ken G. wrote:
> I have been working on this problem for several days and I am not making
> any progress.  I have a group of 18 number, in ascending order, within a
> list.  They ranged from 1 to 39.  Some numbers are duplicated as much as
> three times or as few as none.
> 
> I started with one list containing the numbers.  For example, they are
> listed as like below:
> 
> a = [1, 2, 3, 3, 4]
> 
> I started off with using a loop:
> 
> for j in range (0, 5):
> x = a[0] # for example, 1
> 
> How would I compare '1' with 2, 3, 3, 4?
> 
> Do I need another duplicated list such as b = a and compare a[0] with
> either b[0], b[1], b[2], b[3], b[4]?
> 
> Or do I compare a[0] with a[1], a[2], a[3], a[4]?
> 
> In any event, if a number is listed more than once, I would like to know
> how many times, such as 2 or 3 times.  For example, '3' is listed twice
> within a list.
> 
> TIA,
>

I would do it with a dictionary:
def reps(lst):
dict = {}
for item in lst:
if item in dict:
dict[item] += 1
else:
dict[item] = 1
return dict

This function returns a dictionary with of the number of times each value in 
the list is repeated. Even shorter using dict.setdefault:

def reps(lst):
dict={}
for item in lst:
dict[item] = dict.setdefault(item,0) + 1
return dict

For instance, if lst=[1,2,2,2,4,4,5], then reps(lst) returns
{1: 1, 2: 3, 4: 2, 5: 1}

Using the fact that the list is ordered, one can design a more efficient 
solution (go through the list; if this item is equal to the previous, then it 
is repeated, else, it is a new value). But you list is short enough for this 
direct approach to work.
Hope this helps. Cheers,
Jose
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] string to list

2010-02-10 Thread Jose Amoreira
On Wednesday 10 February 2010 11:26:25 am Owain Clarke wrote:
> Please excuse the obviousness of my question (if it is), but I have
> searched the documentation for how to generate a list e.g. [(1,2),
> (3,4)] from a string "[(1,2), (3,4)]". I wonder if someone could point
> me in the right direction.
> 
> Many thanks
> 
> Owain Clarke
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
Hi
One possibility is to use the eval function. Look at this snippet from an idle 
session:
>>> s="[(1,2),(3,4)]"
>>> lst=eval(s)
>>> lst
[(1, 2), (3, 4)]
>>> lst[0]
(1, 2)
>>> 
Hope this helped
Jose Amoreira
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] help using f2py

2010-01-13 Thread Jose Amoreira
Hello!
I posted this question on the f2py list but since I haven't got any answers 
(yet), I thought I'd try my luck here.

I'm having a hard time wrapping a fortran subroutine into a python module. The 
problem seems to be related to having a subroutine argument to the fortran 
subroutine.
A simple version of my problem is the following. Consider a subroutine (sub), 
which takes as argument a real  array (x), the dimension (n) of that array and 
another subroutine (other_sub) that is to be called by sub :

file sub.f95
--
subroutine sub(x,other_sub,n)
integer::n
real, dimension(n)::x
external other_sub
call other_sub(x)
end subroutine sub
--
The gnu fortran compiler compiles this snippet without any warnings or errors. 
However, when I run it through f2py, all I get is a bunch of errors (see below 
the error output). I'm not sure if this has any relevance but if I change 
argument x to a real scalar (instead of an array), then f2py executes fine and 
the python module is generated.
I just don't get it! Can anybody explain me what I am doing wrong, please? 
Thanks in advance.
Jose Amoreira


Part of the output of f2py -m sub -c sub.f95:
--
creating /tmp/tmpyHp76U/tmp
creating /tmp/tmpyHp76U/tmp/tmpyHp76U
creating /tmp/tmpyHp76U/tmp/tmpyHp76U/src.linux-x86_64-2.6
compile options: '-I/tmp/tmpyHp76U/src.linux-x86_64-2.6 -
I/usr/lib64/python2.6/site-packages/numpy/core/include -
I/usr/include/python2.6 -c'
gcc: /tmp/tmpyHp76U/src.linux-x86_64-2.6/fortranobject.c
gcc: /tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c
/tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c: In function 
‘cb_other_sub_in_sub__user__routines’:
/tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c:306: error: ‘n’ undeclared 
(first use in this function)
/tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c:306: error: (Each undeclared 
identifier is reported only once
/tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c:306: error: for each function 
it appears in.)
/tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c: In function 
‘cb_other_sub_in_sub__user__routines’:
/tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c:306: error: ‘n’ undeclared 
(first use in this function)
/tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c:306: error: (Each undeclared 
identifier is reported only once
/tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c:306: error: for each function 
it appears in.)
error: Command "gcc -pthread -fno-strict-aliasing -DNDEBUG -fmessage-length=0 
-O2 -Wall -D_FORTIFY_SOURCE=2 -fstack-protector -funwind-tables -
fasynchronous-unwind-tables -g -fwrapv -fPIC -I/tmp/tmpyHp76U/src.linux-
x86_64-2.6 -I/usr/lib64/python2.6/site-packages/numpy/core/include -
I/usr/include/python2.6 -c /tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c -o 
/tmp/tmpyHp76U/tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.o" failed with 
exit status 1
-

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


Re: [Tutor] Iterating over two sequences in "parallel"

2009-11-28 Thread Jose Amoreira
Yes, Robert, that does it! Thanks a lot!
Have a nice weekend!
Jose

On Saturday 28 November 2009 10:54:56 am Robert Johansson wrote:
> Hi!
> I want to process corresponding elements of two lists, sequentially. Call
> the
> lists list1 and list2, and assume they have equal lengths. I can do
> something
> like
> 
> for index in range(len(list1)):
> process(list1[index], list2[index])
> 
> But I find it somehow rather ugly, because we generate yet another an list
> for
> the index, when we already have the two we want to process. I know we can
> use
> xrange, but still I find it awkward...
> 
> Instead of the above snippet, I am considering something like
> 
> while list1:
> process(list1.pop(), list2.pop())
> 
> But this has the side effect of emptying both lists, which may not be
> convenient. Of course we can make backup copies of the lists if needed, but
> we
> are then recovering the previous method ugliness...
> 
> Maybe enumerate is what you are looking for?
> 
> list1=range(10)
> list2=range(10,20)
> for index, element in enumerate(list1):
> print element, list2[index]
> 
> /Robert
> 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Iterating over two sequences in "parallel"

2009-11-28 Thread Jose Amoreira
Hi!
I want to process corresponding elements of two lists, sequentially. Call the 
lists list1 and list2, and assume they have equal lengths. I can do something 
like

for index in range(len(list1)):
process(list1[index], list2[index])

But I find it somehow rather ugly, because we generate yet another an list for 
the index, when we already have the two we want to process. I know we can use 
xrange, but still I find it awkward...

Instead of the above snippet, I am considering something like

while list1:
process(list1.pop(), list2.pop())

But this has the side effect of emptying both lists, which may not be 
convenient. Of course we can make backup copies of the lists if needed, but we 
are then recovering the previous method ugliness...

Do you guys have any suggestions regarding this? Thanks
Jose Amoreira
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unexpected Result in Test Sequence

2009-11-16 Thread Jose Amoreira
Hi!
Everytime your program calls function p, list1 is appended to. It keeps on 
getting bigger and bigger. The function adds all the elements of the list, but 
the total is divided by 1000, even if the list is already much longer that 
1000!

And there's another thing. When var1 and var2 are integer, var1/var2 returns 
the integer division, that is, for instance 3/2=1, 9/10=0, etc (try it!).

I bet that if you divide the sum of the values in list1 by len(list1) 
(otherwise reset the list, so that it remains only 1000 element long) and 
replace the line 'print d/1000' with 'print (d*1.0)/len(list1)' (or 'print 
d/1000.0', if you reset the list every time you call p) your problem is over.

Hope this helps!
Cheers
José Amoreira


On Monday 16 November 2009 07:18:52 pm kb1...@aim.com wrote:
> Hello Tutor list.
> I'm running a test to find what the experimental average of a d20 is,
> and came across a strange bug in my code.
> import random
> list1 = []
> def p():
> d = 0
> for number in range(1,1000):
> t = random.randrange(1,19)
> list1.append(t)
> for value in list1:
> d+=value
> print d/1000
> d = 0
> for value in range(1,100):
> p()
>
> It works, but I have a logic error somewhere. It runs, and the results
> have a pattern :
> 9
> 19
> 28
> 37
> 47
> 56
> 66
> 75
> 85
> 94
> 104
> 113
> ...
> ...
> It just adds 10, and every second result, subtracts 1, till it gets to
> 0, and then starts again with 9 in singles, and whatever in the 10's,
> etc.
> What is causing this?
> ___
> 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] OT: Writing code while tired, counterproductive?

2009-11-14 Thread Jose Amoreira
When I get really tired, I sort of slip into an half awaken state. I still 
have my eyes open, I still look at the code, I still think about the problem, 
but suddenly the lines come alive and start arguing with each other (and some 
times arguing with me!), or setting up dates, or singing in choir, all sorts 
of crazy things. That's definitely the time to STOP!, and get some real sleep.

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


Re: [Tutor] namespaces and global

2009-10-14 Thread Jose Amoreira
Alan, Kent, hello!
Thanks for your help. As for your "curiosity", I'm teaching elementary physics 
to undergraduates in computer engineering. Trying to speak my students' 
language, I wanted to show them simple applications that compute numerical 
values for the kinematics formulas of uniformly accelerated motion (the weaker 
students call these formulas Chinese gibberish). 
What I had in mind was to have a module define vectors and vector algebra 
operations using a simple class definition, and another with kinematics 
formulas, like (for uniformly accelerated motion)

def pos(t):
return r0+v0*t+0.5*a*t**2

Here r0 (initial position) v0 (initial velocity) and a (acceleration) are 
global vector parameters which I'd define in an interactive session with the 
students, but I'd rather not include them in the formal parameter list of 
function pos, just because they aren't usually displayed as such in physical 
formulae. I'd like to keep the look and feel of those formulas in the 
interactive python session, without having to type the function definitions in 
that session, but rather import them from a pre-prepared module file.

Anyway, thanks again!
Best Regards,
Jose


On Wednesday 14 October 2009 06:18:28 pm Alan Gauld wrote:
> "Jose Amoreira"  wrote
>
> > Of course I could redefine my module function, including the parameter a
> > in
> > the list of arguments, but I'd rather not.
>
> Why not? That would be good computer science practice and the
> most reliable way to do it. Why do you not want to go down that
> route? Is there a specific reason to use a global variable when
> use of globals is normally considered bad practice?
>
> I'm curious?

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


[Tutor] namespaces and global

2009-10-14 Thread Jose Amoreira
Hello
I'm new to this list. I tried to find the answer to my question but found 
nothing I could really use. I'm sorry if this is a FAQ.

I want to use a variable defined in an interactive session with the python 
interpreter inside a function imported from a module.

For instance, imagine that my module (call it defs.py, for instance) consists 
of:
#coding=utf-8
def f(x):
return a*x

In an interactive session, I import my module:
>>> from defs import f
and I define a global variable a:
>>> a=3
Now I call my module function, expecting to get the triple of the argument I 
feed it with, but, instead, I get an error:
>>> f(2)
Traceback (most recent call last):
  File "", line 1, in 
  File "defs.py", line 3, in f
return a*x
NameError: global name 'a' is not defined
>>>

I tried using the global command in the module, both before the function 
definition and inside the function definition, but none worked as I expected.
Of course I could redefine my module function, including the parameter a in 
the list of arguments, but I'd rather not.

So, my question: is there any way of telling the interpreter to use the value 
of parameters defined in the interactive session when computing the value of a 
module function?
Thanks
ljma

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