Re: Changing the module not taking effect in calling module

2005-09-27 Thread Mikael Olofsson
Gopal wrote:

> I've a module report.py having a set of funtions to open/close/write
> data to a log file. I invoke these functions from another module
> script.py.
> 
> Whenever I'm changing something in report.py, I'm running the file
> (however, it has not effect). After that I'm running script.py again.
> However, the output is not taking effect.
> 
> If I shut the IDLE interpreter and all the other files and then reopen
> again; and then run script.py, the output is taking effect.
> 
> Is there any way to improve it? I'm new to Python.

If I understand you correctly, you are importing your module report in 
script.py. If so, you need reload.

When in IDLE, you have a python process running, in which you execute 
your program. The first time you run script.py after starting IDLE, your 
module report is imported from file. The next time you run script.py, 
there is already a module named report in memory. Then the corresponding 
file will not be executed again. Instead, the one in memory will be used.

What I do when I am developing a module for a program is that I both 
import and reload the module in my main file. Once I think I am done 
developing, I remove the reload statement. So, in your script.py, I 
would write:

import report
reload(report)

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


Dynamic generation of doc-strings of dynamically generated classes

2005-10-17 Thread Mikael Olofsson
Hi!

I've asked Google, but have not found any useful information there.

Situation: I have a base class, say

 >>> class base(object):
 ImportantClassAttribute = None

Now, I want to dynamically generate subclasses of base. That's not a 
problem. However, I very much want those subclasses to have individual 
doc-strings. More precicely, I want that important class attribute to be 
reflected in the doc-string. That's the problem. The only way I've 
managed to accomplish that is something like the following.

 >>> ImportantClassAttribute = 7
 >>> docString = 'The case %s.' % (ImportantClassAttribute,)
 >>> exec('''class new(base):
  """%s"""
  pass ''' % (docString,))
 >>> new.ImportantClassAttribute = ImportantClassAttribute
 >>> new.__doc__
'The case 7.'

This works as intended. The subclasses do get the doc-strings I want 
them to have, and I can live with this solution. But: This solution does 
not strike me as especially beautiful or readable. My first naïve 
attempt was instead the following.

 >>> class new(base):
pass

 >>> new.ImportantClassAttribute = 7
 >>> new.__doc__ = ('The case %(ImportantClassAttribute)s.'
   % new.__dict__)

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 new.__doc__ = ('The case %(ImportantClassAttribute)s.'
TypeError: attribute '__doc__' of 'type' objects is not writable

This is readable to me, but apparently not the way to go, since I'm not 
allowed to replace the doc-string like this. I've also tried a number of 
other ways, but they all stumble on similar reasons.

Any ideas? Am I stuck with the clumsy exec-solution, or are there other 
ways to dynamically generate doc-strings of classes?

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


Re: Dynamic generation of doc-strings of dynamically generated classes

2005-10-18 Thread Mikael Olofsson
Alex Martelli wrote:
> The best way to make classes on the fly is generally to call the
> metaclass with suitable parameters (just like, the best way to make
> instances of any type is generally to call that type):
> 
> derived = type(base)('derived', (base,), {'__doc__': 'zipp'})

and George Sakkis said something similar.

Thanks, both of you. As I expected, there was a much better way than my 
clumsy way. Anyway, this took me to section 3.3.3 in the reference 
manual, and that will help me further.

Thanks again. Back to the keyboard!

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


Re: Would there be support for a more general cmp/__cmp__

2005-10-20 Thread Mikael Olofsson
Antoon Pardon wrote:
> Op 2005-10-20, Duncan Booth schreef <[EMAIL PROTECTED]>:
> 
>>Antoon Pardon wrote:
>>
>>
>>>The problem now is that the cmp protocol has no way to
>>>indicate two objects are incomparable, they are not
>>>equal but neither is one less or greater than the other.
>>
>>If that is the case then you implement __eq__ and __ne__ to return 
>>True/False and make cmp throw an exception. I don't see any need to extend 
>>the cmp protocol.
> 
> 
> That is not sufficient. There are domains where an order exists, but not
> a total order. So for some couples of elements it is possible to say
> one is less than the other, but not for all such couples.
> 
> Your solution wouldn't allow for such a case.

Wouldn't the full power of rich comparisons be enough? See section 3.3.1 
in Python Reference Manual:

 http://www.python.org/doc/2.4.2/ref/customization.html

See methods __lt__, __le__, __eq__, __ne__, __gt__, __ge__.

/MiO


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


Re: how to stop a loop with ESC key? [newbie]

2005-11-08 Thread Mikael Olofsson
Fredrik Lundh wrote:
> works for me, when running it from a stock CPython interpreter in a windows
> console window, with focus set to that window.
> 
> what environment are you using?

Could be IDLE. The code Fredrik proposed works well for me in the Python 
console window, but not in IDLE (thats under XP). I guess that IDLE 
makes use of msvcrt itself. Let's remember that the OP describes himself 
as a newbie in the subject, so he might not know the difference between 
those two interactive environments.

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


Re: any python module to calculate sin, cos, arctan?

2005-11-08 Thread Mikael Olofsson
Shi Mu wrote:
> any python module to calculate sin, cos, arctan?

Try module math. Or cmath if you want the functions to be aware of 
complex numbers.

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


Re: newbie - How do I import automatically?

2005-11-16 Thread Mikael Olofsson
[EMAIL PROTECTED] wrote:
> I tried to put the line
> from btools import *
> in several places in PyShell.py
> but to now avail. It does not work, IDLE does not execute it???

IDLE definitely executes PyShell.py upon startup, since IDLE does not 
even appear on the screen if there is an error in that file. The 
following seems to work for me, in PyShell.py. After importing both sys 
and os,

sys.modules['__main__'].__dict__['os'] = os

Then, if I start IDLE, the module os is directly available.

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


Re: newbie - How do I import automatically?

2005-11-17 Thread Mikael Olofsson
[EMAIL PROTECTED] wrote:
> I tried to do it on my computer (win XP). I put an extra line in
> PyShell.py
> [snip]
> # test
> sys.modules['__main__'].__dict__['os'] = os
> [snip]
> Then when I start idle I get
> 
> IDLE 1.1.1
> 
dir()
> 
> ['__builtins__', '__doc__', '__name__']
> 
> 
> So I don't see 'os'
> 
> Do you see 'os' on your computer. If yes, what could be the difference?

Yes, I do. The following is with IDLE 1.0.3 and Python 2.3.4 on WinXP.

Without the line in PyShell.py:

 IDLE 1.0.3   No Subprocess 
 >>> dir()
 ['__builtins__', '__doc__', '__file__', '__name__', 'main']

With the line in PyShell.py:

 IDLE 1.0.3   No Subprocess 
 >>> dir()
 ['__builtins__', '__doc__', '__file__', '__name__', 'main', 'os']
 >>> os
 

I know nothing about the details of how IDLE work. All I know is what I 
have reported here. I was simply inspired by the following remark from 
Claudio Grondi up-thread:

 > edit the first lines of %SystemDrive%\Python24\Lib\idlelib\PyShell.py

I guess that PyShell.py is imported as a module by IDLE at startup.

One thought, though: Du you have more than one Python installed? If so: 
Could it be that you are editing the wrong PyShell.py?

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


Re: newbie - How do I import automatically?

2005-11-17 Thread Mikael Olofsson
[EMAIL PROTECTED] wrote:
>> I tried to do it on my computer (win XP). I put an extra line in
>> PyShell.py
>> [snip]
>> # test
>> sys.modules['__main__'].__dict__['os'] = os
>> [snip]
>> Then when I start idle I get
>>
>> IDLE 1.1.1
>>
> dir()
>>
>>
>> ['__builtins__', '__doc__', '__name__']
>>
>>
>> So I don't see 'os'
>>
>> Do you see 'os' on your computer. If yes, what could be the difference?
> 
> 

I answered:
> Yes, I do. [snip details]

I have to step back a bit. IDLE seems to work differently depending on 
how it is started. My comments above hold when I start IDLE by 
right-clicking on a python-file and choosing "Edit with IDLE".

If I instead start IDLE itself (from the windows start-menu) I get the 
same behaviour as you do, namely no os around. Another difference, which 
I've noted before is that shell restart is only available when IDLE has 
been started this way.

All this seems to be handled in PyShell.py, but I do not have the time 
to trace that in any detail.

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


Twain problems

2005-01-31 Thread Mikael Olofsson
Hi all!
Sorry for this rather lengthy post. It's a long preamble followed by a few 
questions based on that.

Here's my situation: I am trying to write a specialized scanner utility for 
my own needs, and I want to use the module twain to control my scanner. I 
haven't used the twain module before, which is most certainly why I'm facing 
problems. My problem is to interprete some of the information I get from the 
scanner. The scanner, by the way, is an HP LaserJet 3020, which is a 
multi-toy (printer/scanner/copyer), and I use Python 2.3 on Windows XP.

I set up communication with the scanner as follows (modulo a few ifs to take 
care of unsuccessful connections). Here self is an instance of a class with 
Tkinter.Tk as its base class.

   self.SM = twain.SourceManager(self.winfo_id(),ProductName='foo')
   self.SD = self.SM.OpenSource()
The TWAIN dialog pops up nicely, and I get two options: "hp LaserJet 3020 
TWAIN 1.0 (32-32)" and "WIA-hp LaserJet 3020 1.0 (32-32)". The first choice 
is HPs interface to the scanner, while the second seems to be a scanner 
interface that comes with Windows.

One issue arises if I choose "WIA-hp LaserJet 3020 1.0 (32-32)" and then do 
the following:

   capVal=self.SD.GetCapability(twain.ICAP_CONTRAST)
After that capVal is
   {'StepSize': 1,
   'DefaultValue': 0,
   'CurrentValue': 0,
   'MaxValue': 1000,
   'MinValue': 64536}
My educated guess is that 64536 should be interpreted as -1000, since 64536 
is -1000 modulo 2**16. One problem is that the twain type is not specified. 
So, perhaps I can find the twain type in some other way. The check

   capDef=self.SD.GetCapabilityDefault(twain.ICAP_CONTRAST)
gives me capDef==( 7, 0.0 ). According to my introspection of the twain 
module, the type 7 is twain.TWTY_FIX32. Googling around gives me the 
impression that this corresponds to 32 bits of which the first 16 bits 
correspond to the integer part, and the last 16 bits correspond to the 
fraction part. I thought that the twain module would take care of sign 
issues for me, but it does not seem to do so. OK, I can probably live with 
that. In any case, I guess I'll have to.

OK, that's perhaps not so tough.
Another issue arises if I choose "hp LaserJet 3020 TWAIN 1.0 (32-32)" and 
then do the following:

   capVal=self.SD.GetCapability(twain.ICAP_XSCALING)
After that capVal is
   {'StepSize': 429457408,
   'DefaultValue': 1,
   'CurrentValue': 1,
   'MaxValue': 6,
   'MinValue': 429457408}
Now I'm in trouble. The problem is to interprete capVal['StepSize'] and 
capVal['MinValue']. Both should correspond to some small positive value. 
Here the check

   capDef=self.SD.GetCapabilityDefault(twain.ICAP_XSCALING)
gives me capDef==( 4, 100 ). More introspection says that type 4 is 
twain.TWTY_UINT16. So, again googling around, and I find that this 
corresponds to an unsigned 16bit integer, but that doesn't help me much 
since 429457408 > 2**16. I also notice that capDef[1]==100, while 
capVal['DefaultValue']==1, so there must be a scaling factor of 100 
(percents, yes I know). But that doesn't change the fact that I'm completely 
lost here.

Finally, here are my questions:
Can anyone enlighten me? From the above, I get the impression that the 
dictionary returned by self.SD.GetCapability in these cases give me integer 
approximations of the current and default values. Is that a correct 
interpretation? How should I deal with 429457408 in the example above? Are 
there other twain-type related issues that I haven't seen yet, that I should 
be aware of? Is there some web-resource out there that answers my questions? 
Am I simply missing some information that I might already have? At least I 
haven't been able to find any enlightment in the documentation of the twain 
module or in the TWAIN specification. It seems to me that I need to be very 
careful with the type of the capabilities. How careful should I be?

Googling for things like TWTY_UINT16 typically results in what I interprete 
as C or C++ code, which does not help me much. I'm less fluent in C or C++ 
than I am in Italian (I can order a beer and buy postcards or stamps, that's 
more or less it).

I-cannot-order-a-beer-in-C-but-I-can-in-Python-ly yours
/Mikael Olofsson
Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet
---
E-Mail:  [EMAIL PROTECTED]
WWW: http://www.dtr.isy.liu.se/en/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
---
Linköpings kammarkör: www.kammarkoren.com   Vi söker tenorer och basar! 

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


Re: aproximate a number

2005-08-29 Thread Mikael Olofsson
Michael Sparks wrote:
> def approx(x):
> return int(x+1.0)

I doubt this is what the OP is looking for.

 >>> approx(3.2)
4
 >>> approx(3.0)
4

Others have pointed to math.ceil, which is most likely what the OP wants.

/Mikael Olofsson
Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet

---
E-Mail:  [EMAIL PROTECTED]
WWW: http://www.dtr.isy.liu.se/en/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
---
Linköpings kammarkör: www.kammarkoren.com   Vi söker tenorer och basar!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to join two Dictionary together?

2005-08-30 Thread Mikael Olofsson
DENG wrote:
> dict1={...something...}
> dict2={...somethind else ..}
> dict1 + dict2
> 
> that's does works ..:(, it's not like List...
> anyone can tell me how to get it?

I would do the following in most cases.

 >>> dict1={'a':'A'}
 >>> dict2={'b':'B'}
 >>> dict3=dict1.copy()
 >>> dict3
{'a': 'A'}
 >>> dict3.update(dict2)
 >>> dict3
{'a': 'A', 'b': 'B'}

HTH
/Mikael Olofsson

Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet

---
E-Mail:  [EMAIL PROTECTED]
WWW: http://www.dtr.isy.liu.se/en/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
---
Linköpings kammarkör: www.kammarkoren.com   Vi söker tenorer och basar!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Optional algol syntax style

2005-09-05 Thread Mikael Olofsson
Sokolov Yura wrote:
> I think, allowing to specify blocks with algol style (for-end, if-end, 
> etc) will allow to write easy php-like templates
> and would attract new web developers to python (as php and ruby do).
> It can be straight compilled into Python bytecode cause there is 
> one-to-one transformation.
 > [snip details]

Standard answer to this kind of question:

You can already do that in Python. It's spelled #end.

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


Re: working with VERY large 'float' and 'complex' types

2005-09-15 Thread Mikael Olofsson
Paul Rubin calculates exp(1000.0):
> You could rearrange your formulas to not need such big numbers:
> 
> x = 1000.
> log10_z = x / math.log(10)
> c,m = divmod(log10_z, 1.)
> print 'z = %.5fE%d' % (10.**c, m)

Nice approach. We should never forget that we do have mathematical 
skills beside the computers. But, shouldn't you switch c and m in the 
last row?

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


Re: Tkinter add_cascade option_add

2005-09-15 Thread Mikael Olofsson
Eric Brunel wrote in reply to Bob Greschke:
> I'm still not sure what your exact requirements are. Do you want to have 
> a different font for the menu bar labels and the menu items and to set 
> them via an option_add? If it is what you want, I don't think you can do 
> it: the menus in the menu bar are just ordinary items for tk, and you 
> can't control separately the different kind of menu items. 

I guess he has the same problem as I have. See sample code:

from Tkinter import *
class App(Tk):
 def __init__(self):
 Tk.__init__(self)
 self.option_add('*Menu.font', 'helvetica 24 bold')
 self.menuBar=Menu(self)
 self.fileMenu=Menu(self.menuBar,tearoff=0)
 self.subMenu=Menu(self.fileMenu)
 self.fileMenu.add_cascade(label='foo', menu=self.subMenu)
 self.subMenu.add_command(label='bar',command=self.foo)
 self.subMenu.add_command(label='baz',command=self.foo)
 self.fileMenu.add_command(label='Quit',command=self.quit)
 self.menuBar.add_cascade(label='File',menu=self.fileMenu)
 self.config(menu=self.menuBar)
 def foo(self):
 pass
app=App()
app.mainloop()

What happens on my WinXP-box when I run this code is that the menu bar 
still is displayed in the standard font, which seems to be Helvetica 8. 
I.e. The text 'File' is still small, while everything else in the menus 
is displayed in Helvetica 24 bold. Adding font=... to any of the 
commands above does not change the appearance of 'File'. I have no 
problems changing the appearance of any individual text in the menu 
except for the mentioned 'File'. I can change the appearance of 'foo' in 
the self.fileMenu.add_cascade row, but nothing happens to 'File' if I 
try to specify a font in the self.menuBar.add_cascade row. Doesn't that 
seem a bit peculiar?

But... The example you gave does not change the appearance of the menus 
at all on my machine. I guess it was supposed to?

Is this simply a Windows-issue that cannot easily be solved? Or is it 
possibly so that this just happens to be a problem on a few 
ill-configured computers? Or am I possibly blind?

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


Re: plateform info.

2005-09-20 Thread Mikael Olofsson
Monu Agrawal wrote:
> Hi I want to know whether the program is being run on windows or on
> Xnix. Is there any variable or method which tells me that it's windows?

Will this help?

 >>> import sys
 >>> sys.platform
'win32'

There is also the platform module, that can give you a lot more 
information about the your platform. Try help(platform).

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


Re: Help w/ easy python problem

2005-09-22 Thread Mikael Olofsson
[EMAIL PROTECTED] wrote:
> I am very much a beginner to python.  I have been working on writing a
> very simple program and cannot get it and was hoping someone could help
> me out.  Basically i need to write a code to print a sin curve running
> down the page from top to bottom.  The trick is I have to do this using
> only 7-8 lines of code.  Any ideas?


This sounds like homework, and I think you should do that on your own. 
One hint, though: You could take a look at the standard module math.

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


Re: Galois field

2004-12-03 Thread Mikael Olofsson
Roie Kerstein wrote:
I am looking for a python package that deals with galois fields.
Does anybody know where can I find it?
Googling for
   python "finite field"
reveals among other things the URLs
   http://www.hpcf.upr.edu/~humberto/software/fields/
   http://www.csua.berkeley.edu/~emin/source_code/py_ecc/
I have not looked into those, but at least the first one seems to be in a 
very early state, since its version number is 0.1.1. The second one contains 
code for handling Reed-Solomon codes, which among other things includes 
arithmetic for finite fields.

Good luck!
/Mikael Olofsson
Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet
---
E-Mail:  [EMAIL PROTECTED]
WWW: http://www.dtr.isy.liu.se/en/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
---
Linköpings kammarkör: www.kammarkoren.com   Vi söker tenorer och basar! 

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


Re: Galois field

2004-12-03 Thread Mikael Olofsson
Roie Kerstein wrote:
Thank you very much!
However, I lack two important things in the packages introduced there:
1. There is only element arithmetic - no polynomials, in which I have 
need.
2. there is support only for fields of order 2^p, while I need fields of
prime order.
You still helped me, as before I searched for galois fields and found
nothing, and search for finite fields yields more results.
Off topic for the list, but possibly on topic for this thread:
At our department we use Magma (http://magma.maths.usyd.edu.au/) for finite 
field arithmetic and error control codes. Magma has nothing to do with 
Python, instead it is a very mature tool of its own, mainly for descrete 
math. It knows what a permutation group is, it knows what GF(81) is, and 
much more. Check out the handbook (Magma on-line help) on the web site and 
be impressed. You will find finite fields under Basic Rings. Magma is not 
free, though, and licence fees vary depending on who is buying the licence, 
see the web site for details. Note that under certain circumstances you may 
be eligible for a free version. If you have access to Magma where you are, 
do consider using it.

An example Magma session:
banin:~> magma
Magma V2.8-9  Fri Dec  3 2004 13:17:54 on banin[Seed = 735720219]
Type ? for help.  Type -D to quit.
R:=PolynomialAlgebra(GF(3));
F:=GF(27);
for el in F do
for>  print el, "   ", MinimalPolynomial(el);
for> end for;
1 x + 2
a x^3 + 2*x + 1
a^2 x^3 + x^2 + x + 2
a^3 x^3 + 2*x + 1
a^4 x^3 + x^2 + 2
a^5 x^3 + 2*x^2 + x + 1
a^6 x^3 + x^2 + x + 2
a^7 x^3 + x^2 + 2*x + 1
a^8 x^3 + 2*x^2 + 2*x + 2
a^9 x^3 + 2*x + 1
a^10 x^3 + x^2 + 2
a^11 x^3 + x^2 + 2*x + 1
a^12 x^3 + x^2 + 2
2 x + 1
a^14 x^3 + 2*x + 2
a^15 x^3 + 2*x^2 + x + 1
a^16 x^3 + 2*x + 2
a^17 x^3 + 2*x^2 + 1
a^18 x^3 + x^2 + x + 2
a^19 x^3 + 2*x^2 + x + 1
a^20 x^3 + 2*x^2 + 2*x + 2
a^21 x^3 + x^2 + 2*x + 1
a^22 x^3 + 2*x + 2
a^23 x^3 + 2*x^2 + 1
a^24 x^3 + 2*x^2 + 2*x + 2
a^25 x^3 + 2*x^2 + 1
0 x

Regards
/Mikael Olofsson
Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet
---
E-Mail:  [EMAIL PROTECTED]
WWW: http://www.dtr.isy.liu.se/en/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
---
Linköpings kammarkör: www.kammarkoren.com   Vi söker tenorer och basar! 

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


Re: Begniner Question

2005-03-21 Thread Mikael Olofsson
"Glen" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
if int(choice)==2:
else:
  pass
File "./Code.py", line 20
  else:
 ^
IndentationError: expeted an indented block
What am I doing wrong?
As the error trace informs you, Python expexts an indented block. You need 
to put something between if and else, at least a pass.

Regards
--
/Mikael Olofsson
Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet
---
E-Mail:  [EMAIL PROTECTED]
WWW: http://www.dtr.isy.liu.se/en/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
---
Linköpings kammarkör: www.kammarkoren.com   Vi söker tenorer och basar! 

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


Re: Printable version of Python tutorila

2005-04-14 Thread Mikael Olofsson
<[EMAIL PROTECTED]> wrote:
I liked the python tutorial (
http://www.python.org/doc/current/tut/tut.html ) very much.
Now i want to print this tutorial.
Where do i get a printable version of the document?
http://www.python.org/doc/current/download.html
Regards
/Mikael Olofsson
Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet
---
E-Mail:  [EMAIL PROTECTED]
WWW: http://www.dtr.isy.liu.se/en/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
---
Linköpings kammarkör: www.kammarkoren.com   Vi söker tenorer och basar! 

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


Re: OT: excellent book on information theory

2006-01-19 Thread Mikael Olofsson
Terry Hancock wrote:
"Tim Peters" <[EMAIL PROTECTED]> wrote:
>>   UK:Harry smiled vaguely back
>>   US:Harry smiled back vaguely

Terry Hancock wrote:
> I know you are pointing out the triviality of this, since
> both US and UK English allow either placement -- but is it
> really preferred style in the UK to put the adverb right
> before the verb?  In US English, the end of the clause
> (or the beginning) is probably more common.

I appreciate your desire to put the thread on (Python) topic, but as I 
see this discussion, it really has to do with respect for the author, 
but also respect for the reader. The UK version is most likely the way 
the author intended it to be. Then that is the way the text should be, 
regardless if it is preferred style or not, under the assumption that 
English is English is English.

One question here is: Are US English and UK English different languages 
or not? If they are, a translation is in place. If they are not, the 
text should have been left as is. I guess the answer is:
-Well, sort of...
And that is probably the reason why opinions differ here, and also the 
reason why the American publisher has made some changes, but left most 
parts unchanged.

A related important question is: Does the US version communicate the 
same thing (meaning aswell as feeling) to the American reader as the UK 
version communicates to the British reader? That should always be the 
objective for any translator. It also means that if the author in the UK 
version uses non-standard UK English, then the US version should use 
non-standard US English.

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


Re: Why do this?

2006-10-05 Thread Mikael Olofsson


Matthew Warren wrote:
> I learned over the years to do things like the following, and I like
> doing it like this because of readability, something Python seems to
> focus on :-
>
> Print "There are "+number+" ways to skin a "+furryanimal
>
> But nowadays, I see things like this all over the place;
>
> print("There are %s ways to skin a %s" % (number, furryanimal))
>
> Now I understand there can be additional formatting benefits when
> dealing with numbers, decimal places etc.. But to me, for strings, the
> second case is much harder to read than the first.
>   

I agree that the second alternative isn't too readable. It is also not 
too maintainable. My version of the above is most often

print "There are %(number)s ways to skin a %(furryanimal)s." % vars()

Readable and maintainable.

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


Re: deleteing item from a copy of a list

2006-11-14 Thread Mikael Olofsson
timmy wrote:
> i make a copy of a list, and delete an item from it and it deletes it 
> from the orginal as well, what the hell is going on?!?!?!
>
> #create the staff copy of the roster
>   Roster2 = []
>   for ShiftLine in Roster:
>   #delete phone number from staff copy
>   Roster2.append(ShiftLine)
>   del Roster2[len(Roster2)-1][1]
>
> Roster2 should have nothing to do with Roster, right??? doing a print of 
> both lists confirms that the phone number has been removed from both
>   

First of all, you could have said

del Roster2[-1][1]

since negative indices count backwards from the end of the list. This 
has nothing to do with your problem, though.

Fredrik has already given you a correct, somewhat condensed, answer. Let 
me elaborate. I guess that Roster is a list of lists. Then actually, it 
is a list of references to lists (really a reference to a list of 
references to lists). Your for-loop makes Roster2 a shallow copy of 
Roster, i.e. Roster2 is a new list with references to the _same_ 
sublists as in Roster. So, Roster2[-1] references the same object as 
Roster[-1], not a copy of it. To get copies, you could change your 
.append-line to

Roster2.append(ShiftLine[:])

which gives you shallow copies of the sublists. If there are mutables in 
the sublists, you may still get into trouble. In that case, maybe you 
should take a look at copy.deepcopy.

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


Re: Running Python scripts under a different user

2006-05-31 Thread Mikael Olofsson
Laszlo Nagy wrote:
> For Windows, you can use the 'runas.exe' program. But it requires a 
> password too.

Or you can get a copy of the shareware program RunAsProfessional, which 
I use for my kids stupid games that necessarily has to be run by an 
admin. The price I paid was 10 Euro, which I still think was money well 
spent. IIRC you get a 30 days trial version for free.

http://freedownloads.rbytes.net/cat/desktop/other3/runas-professional/

It does the same thing as RunAs, but you do not need to type the 
password every time you run your program. Instead the password is stored 
encrypted in the file you launch. I do not know what encryption is used, 
or how safe the encryption is. My needs are simply to make sure that my 
kids do not destroy anything by mistake. Sure, the stupid game may be 
designed to destroy, but that's another issue.

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


Re: cos: "Integer Required"?!?!?!?

2006-06-08 Thread Mikael Olofsson
moonman wrote:
> print self.ACphi, type(self.ACphi) yields:
> 19412557 
> 
> value = XPLMGetDataf(self.ACphi); print value  type(value ) yields:
> -0.674469709396 
> 
> print math.radians(XPLMGetDataf(self.ACphi)),
> type(math.radians(XPLMGetDataf(self.ACphi))) yields:
> 
> TypeError
> :
> an integer is required
> 
> Am I totally missing something about 'math'. Does it really expect an
> int?

Not my Python:

 >>> math.radians(-0.674469709396)
-0.011771717133929535

This all seems very confusing. Have you tried exactly the above?

Do you perhaps have a module of your own called math, that Python might 
be importing? Or is your math not a module, but some other object that 
happens to have a method called radians, that expects an int? Or have 
you accidentally redefined math.radians?

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


Changing behaviour of namespaces

2006-09-21 Thread Mikael Olofsson
Hi!

This is in Python 2.3.4 under WinXP.

I have a situation where I think changing the behaviour of a namespace 
would be very nice. The goal is to be able to run a python file from 
another in a separate namespace in such a way that a NameError is not 
raised if a non-existing variable is used in the file. The file that I 
want to run is taken out of context, and some needed variables may be 
missing that are normally there when used in the intended context. OK! 
When I run it out of context, I do not want the execution to stop 
half-way through the file based on NameErrors, instead a predefined 
dummy variable should be used. The question is: Can I achieve that?

Google didn't give me much, so I experimented a bit: First, I created a 
dummy object, which is meant to be used when a variable is missing:

class dummyClass(object):
pass
dummyObject = dummyClass()

The actual dummy object is supposed to be a bit more complicated than 
that. The next step was to subclass dict:

class forgivingDict(dict):
def __init__(self,*args,**kwargs):
dict.__init__(self,*args,**kwargs)
def __getitem__(self,key):
print 'Getting', key
try:
return dict.__getitem__(self,key)
except KeyError:
return dummyObject
def __setitem__(self,key,value):
print 'Setting', key, 'to', value
dict.__setitem__(self,key,value)
def __contains__(self,item):
return True
def __repr__(self):
return 'forgivingDict(%s)' % (dict.__repr__(self),)

Then I tried to execute a file using a forgivingDict() as namespace:

ns = forgivingDict()
execfile(filePath, ns)

A file containing the following passes perfectly OK:

a = 0
b = a

But a file containing the following produces a NameError:

b = a

The error traceback for the interested:

Traceback (most recent call last):
  File "//charm/mikael/My 
Documents/Programmering/Python/Tester/voidTest.py", line 130, in ?
execfile('test2.py', ns)
  File "test2.py", line 1, in ?
b = a
NameError: name 'a' is not defined

Now, that is exactly what is to expect if ns is a dict(), but I was 
hoping that b would have ended up as dummyObject when ns is a 
forgivingDict(). One thing: Nothing is printed out when execfile-ing the 
files, which means that the methods forgivingDict.__getitem__ and 
forgivingDict.__setitem__ are never used. My guess was that the 
execution done by execfile uses dict.__getitem__(ns, key) and 
dict.__setitem__(ns,key,value) instead of ns[key] and ns[key]=value when 
getting and setting variables. That is probably intentional from the 
developers and done that way for a good reason.

Alternative test: I've tried to replace __builtin__.dict with my 
forgivingDict, slightly modified to make sure that the inheritance still 
works, which didn't change anything. So it seams that the execution done 
by execfile does *not* use dict.__getitem__(ns, key) and 
dict.__setitem__(ns,key,value) after all, but something else. Probably 
the original dict is around somewhere else, and execfile uses the 
corresponding methods of that.

My approach seems flawed. Any ideas? Can I somehow execute a complete 
file even if there are non-existent variables used somewhere? A 
try-except around the execfile statement is not an alternative, since 
that stops the execution where the error occurs.

Should I perhaps read up on the compiler module? I mean: Using the 
compiler module to analyze the content of the file, and based on that 
updating my namespace before executing the file.

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


Re: Changing behaviour of namespaces - solved, I think

2006-09-21 Thread Mikael Olofsson
Peter Otten wrote:
> To feed an arbitrary mapping object to execfile() you need to upgrade to
> Python 2.4.

Thanks! As clear as possible. I will do that.

FYI: I think I managed to achieve what I want in Py2.3 using the 
compiler module:

def getNamesFromAstNode(node,varSet):
if node.__class__ in (compiler.ast.Global,compiler.ast.Import):
varSet.union_update(node.names)
if node.__class__ in (compiler.ast.Name,):
varSet.add(node.name)
for subNode in node.getChildNodes():
getNamesFromAstNode(subNode,varSet)

# Get all variable names that are referenced in the file:
varSet = sets.Set()
mainNode = compiler.parseFile(filePath)
getNamesFromAstNode(mainNode,varSet)

# Define a namespace and update it:
ns = {}
for varName in varSet:
ns[varName] = dummyObject

# Execute the file without NameErrors:
execfile(filePath,ns)

Batteries included!

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


Re: Changing behaviour of namespaces - solved, I think

2006-09-21 Thread Mikael Olofsson
Peter Otten wrote:
> Clearly more elegant than:
>
>   
 print open(filename).read()
 
> b = a
>   
 dummy = 42
 names = []
 while 1:
 
> ... ns = dict((n, dummy) for n in names)
> ... try:
> ... execfile(filename, ns)
> ... except NameError, e:
> ... names.append(e[0][6:-16])
> ... else:
> ... break
> ...
>   
 names
 
> ['a']
>   

That sure is nicer. My solution looks like shooting mosquitoes with an 
elephant rifle i comparison. Thanks.

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


Re: AN Intorduction to Tkinter

2006-09-27 Thread Mikael Olofsson
The following is the answer I gave on [EMAIL PROTECTED] Perhaps Fredrik can 
elaborate on the status of different versions of his excellent publication.


Tanner Ruschman wrote about "An Introduction to Tkinter" by Fredrik Lundh:

> > When I saw that it was written 
> > (actually, copyrighted) in 1999, I figured that a new(er) version of 
> > Tkinter had come out since then, changing how some of the code examples 
> > work.
> >
> > Does anybody know of a guide as comprehensive as this, but written for 
> > one of the more recent Tkinter modules?
>   

You probably mean

http://www.pythonware.com/library/tkinter/introduction/

which is copyrighted 1999. There is also

http://effbot.org/tkinterbook/

which I think is the most recent version of it. It states that it is 
last updated in November 2005.

HTH
/Mikael Olofsson

Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet

---
E-Mail:  [EMAIL PROTECTED]
WWW: http://www.dtr.isy.liu.se/en/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
---
Linköpings kammarkör: www.kammarkoren.com   Vi söker tenorer och basar! 

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


Re: How can I make a class that can be converted into an int?

2006-10-02 Thread Mikael Olofsson


Matthew Wilson wrote:
> What are the internal methods that I need to define on any class so that
> this code can work?
>
> c = C("three")
>
> i = int(c) # i is 3

 From Python Reference Manual, section 3.4.7 Emulating numeric types:

__complex__( self)
__int__( self)
__long__( self)
__float__( self)
 Called to implement the built-in functions complex(), int(), 
long(), and float(). Should return a value of the appropriate type.

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


Re: file backup in windows

2006-11-22 Thread Mikael Olofsson
k.i.n.g. wrote:
> [snip code]
> The above code was fine while printing, when I am trying to use this
> (outlook_path) to use as source path it is giving file permission error
> can you please clarify this

Did you follow the link that Fredrik Lundh gave you?

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


Re: Tk.quit() now working!

2006-01-31 Thread Mikael Olofsson
Fredrik Lundh wrote:
>>how do you run your Tkinter program ?

al pacino wrote:
> like? i was testing it in windows (interactive interpreter)

What Fredrik probably means is: Did you by any chance start it from 
IDLE? In that case it will not work. It doesn't for me. The reason - 
I've been told - is that IDLE itself is a tkinter application.

If you instead start it by simply double-clicking on its icon, as you 
would start anything else in Windows, it should work as expected. It 
does for me, on Win XP Pro.

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


Re: Create dict from two lists

2006-02-10 Thread Mikael Olofsson
py wrote:
> Thanks, itertools.izip and just zip work great.  However, I should have
> mentioned this, is that I need to keep the new dictionary sorted.

Dictionaries aren't sorted. Period.

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


Re: Soduku

2006-02-15 Thread Mikael Olofsson
Jonathan Gardner wrote:
> How do you have a 16x16 grid for soduku? Are you using 16 digits? 0-F?
> 
> The one I am using has 9 digits, 9 squares of 9 cells each, or 9x9
> cells.

What alphabet you use is irrelevant. Sudokus has really nothing to do 
with numbers. You can use numbers, as well as letters, fruits, or car 
models. Numbers just happen to be nice to use as alphabet for fairly 
small sudokus. The hobby electronics magazine elektor at

 http://www.elektor-electronics.co.uk/

uses 0-F for their 16x16 sudokus.

You can make sudokus of more or less any size. In the kids department at

 http://www.dailysudoku.co.uk

you can find 4x4 and 6x6 grids. Apart from those and the standard 9x9, I 
have also seen 12x12, 16x16 and 25x25. You could make them 8x8 or 99x99 
if you wish. Those numbers should be non-primes, though, since the 
pattern of sub-blocks breaks if the numbers are primes.

Perhaps I should mention the three-dimensional one (9x9x9) that someone 
showed me at work. That particular one was a bore, since it contained 
too much patterns. Or the two orthogonal ones, where you have two 9x9 
sudokus in one with interrelations...

Finally, dailysudoku also has what they call squiggly sudokus, e.g.

 
http://www.dailysudoku.co.uk/sudoku/squiggly/archive.shtml?year=2006&month=02&day=15

By the way, if I'm not completely mistaken, there are only two 
non-equivalent solutions to the 4x4 grid. The equivalence relations 
taken into account are then the following:

   Permutations of the alphabet.
   Interchanging interchangeable rows or columns.
   Transpose - as in matrix transpose - of the whole grid.

Enough off-topic for now
/MiO
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter Checkboxes

2006-02-20 Thread Mikael Olofsson
D wrote:
> Ok, I'm sure this is something extremely simple that I'm missing,
> but..how do I set a variable in a Tkinter Checkbox?  i.e. I have a
> variable "test" - if the checkbox is selected, I want to set test=1,
> otherwise 0.  Thanks!
> 

http://www.pythonware.com/library/tkinter/introduction/x3897-patterns.htm


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


Re: Little tool - but very big size... :-(

2006-02-21 Thread Mikael Olofsson
Durumdara wrote:
> But it have very big size: 11 MB... :-(
> 
> The dist directory:
> [snip relatively small files]
> 2005.09.28.  12:41 1 867 776 python24.dll
> [snip relatively small files]
> 2006.01.10.  19:09 4 943 872 wxmsw26uh_vc.dll
> [snip relatively small files]
>  20 file11 485 758 byte
> 
> I need to have more compressed result. Can I compress dll-s, pyd-s with
> Py2Exe ?
> Can I decrease the total size with something ?

I've snipped out the relatively small files above. Yes, true, some of 
them consume about 0.5MB each.

It seems to me that your choice of GUI framework is a major cost here. I 
have never used wxpython. Instead my GUIs are based on tkinter. What I 
typically end up with is roughly 7MB. My last example ended up in 7.5MB. 
Zipping the whole thing reduces that to 2.6MB. Is it completly out of 
the question to have a compressed version of the tool on your memory 
stick, and to decompress it on the examined computer before actually 
running the tool?

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


Re: Writing an applilcation that can easily adapt to any language

2006-03-01 Thread Mikael Olofsson
Chance Ginger wrote:
> I am rather new at Python so I want to get it right. What I am doing
> is writing a rather large application with plenty of places that 
> strings will be used. Most of the strings involve statements of
> one kind or another. 
> 
> I would like to make it easy for the support people to port the
> application from one language to another, German, Spanish, etc. 
> Rather than make them search all over for the strings to replace
> is there a library that I can use to make this all easier? I
> keep thinking of resources in Java, as an example. Is there 
> anything like it in Python?

Brono's suggestion is most certainly very good. If you are looking for 
something more light-weight, you might enjoy my module language that I 
include below. The idea is to have everything language-specific in one 
module, that is imported everywhere it is needed in my application. Consider

 import language
 fileText = language.texts['file']

After this, fileText is either 'File' or 'Arkiv' depending on if 
language.lang is 'en' or 'sv'. The docstrings should be enough 
documentation to use the module. perhaps you might want to split the 
module up into two modules, one containing the class, and one containing 
the texts.

/MiO



And here is the module:

# -*- coding: cp1252 -*-

"""Module language:
The most important object made available here is the following:

 handleLanguage
 A class that handles information in different languages. See the
 doc-string of this class for more information.

 texts
 A dictionary containing objects of the class handleLanguage.

 lang
 A string representing chosen language.

 availableLanguages
 A list of strings representing available languages. The first
 item is the default fallback language if lang fails.

"""

lang='en'
availableLanguages=[lang]


class handleLanguage(dict):
 """class handleLanguage:
 A class that handles information in different languages as strings.
 This class is instantiated as follows:

 foo=handleLanguage(sv='blah',en='blahblah')

 After that we have foo['sv']=='blah' and foo['en']=='blahblah'.
 Also, the languages 'sv' and 'en' will have been appended to the
 module level list availableLanguages if they were not in that list
 before.

 Now let foo be any instance of this class. The real funtionality of
 this class is that str(foo) depends on the module variables lang and
 availableLanguages. More precicely str(foo)==foo[x] where x chosen
 according to the following.

 if lang in foo: x=lang
 elif availableLanguages[0] in foo: x=availableLanguages[0]
 elif 'en' in foo: x='en'
 else: x=foo.keys()[0].

 If none of this works, then we have str(foo)=='??', which only
 happens if foo does not contain any language.
 """
 def __init__(self,**kwargs):
 dict.__init__(self,**kwargs)
 for key in kwargs:
 if key not in availableLanguages:
 availableLanguages.append(key)
 def __str__(self):
 try:
 return self[lang]
 except KeyError:
 if availableLangages[0] in self:
 return self[availableLangages[0]]
 elif 'en' in self:
 return self['en']
 elif self:
 return self[self.keys()[0]]
 else:
 return '??'
 def __add__(self,other):
 if not isinstance(other,dict):
 foo,other=self.__coerce__(other)
 new=handleLanguage(**dict(other))
 new.update(self)
 for key in self:
 if key in other:
 new[key]=self[key]+other[key]
 return new
 def __radd__(self,other):
 if not isinstance(other,dict):
 foo,other=self.__coerce__(other)
 new=handleLanguage(**dict(other))
 new.update(self)
 for key in self:
 if key in other:
 new[key]=other[key]+self[key]
 return new
 def __coerce__(self,other):
 new=handleLanguage()
 for key in self:
 new[key]=str(other)
 return self,new

texts={
 # Common texts
 'appName':handleLanguage(
 sv='Uppgiftshanteraren',
 en='TaskManager',
 ),
 'foo':handleLanguage(
 sv='foo',
 en='foo',
 ),
 # File menu
 'file':handleLanguage(
 sv='Arkiv',
 en='File',
 ),
 'help':handleLanguage(
 sv='Hjälp',
 en='Help',
 ),
 'open':handleLanguage(
 sv='Öppna',
 en='Open',
 ),
 }

if __name__=="__main__":
 keys=texts.keys()
 keys.sort()
 for lang in availableLanguages:
 print lang
 for key in keys:
 print '   ',key+':',texts[key]
 print
 print 'Done'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a re problem

2005-05-20 Thread Mikael Olofsson


cheng wrote:

>>>p.sub('','%s') % "a\nbc"
>>>  
>>>
>'a\nbc'
>
>is it anyone got some idea why it happen?
>

Make that

p.sub('','%s' % "a\nbc")


Regards
/Mikael Olofsson

Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet

---
E-Mail:  [EMAIL PROTECTED]
WWW: http://www.dtr.isy.liu.se/en/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
---
Linköpings kammarkör: www.kammarkoren.com   Vi söker tenorer och basar! 

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


Re: prime number

2005-05-31 Thread Mikael Olofsson
lostinpython wrote:
> What civil engineers need with all this programming is beyond me.  We
> have to learn another language to program our CADD software, which I
> find much easier than this.  

According to my experience, almost every engineer - civil or not - uses 
programming at least occationally. So every engineering education 
program should involve at least some programming.

/Mikael Olofsson

Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet

---
E-Mail:  [EMAIL PROTECTED]
WWW: http://www.dtr.isy.liu.se/en/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
---
Linköpings kammarkör: www.kammarkoren.com   Vi söker tenorer och basar!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: c[:]()

2007-05-31 Thread Mikael Olofsson
Warren Stringer wrote:
> I want to call every object in a tupple, like so:
> [snip examples]
> Why? Because I want to make Python calls from a cell phone. 
> Every keystroke is precious; even list comprehension is too much. 

If you are going to do this just a few times in your program, I cannot 
help. But: If you want to do it several times, perhaps you have space 
for an initial class definition, like so:

class CallableList(list):
def __call__(self,*args,**kwargs):
return [f(*args,**kwargs) for f in self]

def a(): return 'a called'
def b(): return 'b called'
c = CallableList([a,b])()

You might want to trim the class to fit your needs, perhaps use a 
shorter name, and perhaps you don't need to handle arguments. Can the 
class be placed in a module, so that it only needs to be typed once in 
your application?

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


Re: Combinatorial of elements in Python?

2007-08-15 Thread Mikael Olofsson
Sebastian Bassi wrote:
> I have 2 (or more) groups of elements, and I want to get all possible
> unique combinations from all of them. Is there a build-in method to do
> it?
>
> ADictionary={"one":["A","B","C","D"],"two":["H","I"]}
>
> I want to have all possible combinations from "one" and "two", that is:
> [snip]

Not at all complicated. My solution:

 >>> A={'one':['A','B','C','D'],'two':['H','I']}
 >>> [x+y for x in A['one'] for y in A['two']]
['AH', 'AI', 'BH', 'BI', 'CH', 'CI', 'DH', 'DI']

HTH
/MiO

-- 
/Mikael Olofsson
Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet

---
E-Mail:  [EMAIL PROTECTED]
WWW: http://www.dtr.isy.liu.se/en/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
---
Linköpings kammarkör: www.kammarkoren.com   Vi söker tenorer och basar! 

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

Re: Combinatorial of elements in Python?

2007-08-15 Thread Mikael Olofsson


Sebastian Bassi wrote:
> Hello, could you do it for an indefinite number of elements? You did
> it for a fixed (2) number of elements. I wonder if this could be done
> for all members in a dictionary.

What is unclear here is in what order the keys should be visited. The 
following assumes that the keys should be considered in alphanumeric order.

 >>> def combine(d):
if not d:
return []
elif len(d)==1:
return d.values()[0]
else:
keys = d.keys()
keys.sort()
leftKeys = keys[0:len(keys)//2]
rightKeys = keys[len(keys)//2:]
leftDict = dict((key,d[key]) for key in leftKeys)
rightDict = dict((key,d[key]) for key in rightKeys)
return [x+y for x in combine(leftDict) for y in combine(rightDict)]

   
 >>> 
A={'field1':['a','A'],'field2':['b','B'],'field3':['c','C'],'field4':['d','D']}
 >>> combine(A)
['abcd', 'abcD', 'abCd', 'abCD', 'aBcd', 'aBcD', 'aBCd', 'aBCD', 'Abcd', 
'AbcD', 'AbCd', 'AbCD', 'ABcd', 'ABcD', 'ABCd', 'ABCD']


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


Re: Combinatorial of elements in Python?

2007-08-16 Thread Mikael Olofsson
Sebastian Bassi wrote:
> On 8/15/07, Mikael Olofsson <[EMAIL PROTECTED]> wrote:
>   
>> What is unclear here is in what order the keys should be visited. The
>> following assumes that the keys should be considered in alphanumeric order.
>> 
>
> Yes, my fault. The orden should be given by a string, like:
>
> DCDBA
> Using this dictionay.
> A={'A':['1','2'],'B':['4','5'],'C':['6','7','8'],'D':['9']}
>
> Should return:
>
> '96941'
> '97941'
> '97942'
> '96942'
> '98941'
> '98942'
> '96951'
> '97951'
> '97952'
> '96952'
> '98951'
> '98952'

OK, seems like you need to add a second argument to the function 
specifying this order. I leave that to you.

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


Re: beginner, idiomatic python

2007-08-24 Thread Mikael Olofsson


bambam wrote:
>
> In this case it doesn't matter - my lists don't contain
> duplicate elements this time - but I have worked with lists in
> money market and in inventory, and finding the intersection
> and difference for matching off and netting out are standard
> operations.

I would use a list comprehension for that case:

A = ['a','b','c','a','c','d']
U = ['a','b','e']
B = [x for x in A if x in U]

The result would be B==['a','b','a']

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


Re: Tell me the truth

2007-03-08 Thread Mikael Olofsson


[EMAIL PROTECTED] wrote:
> If I take into account the fact that 'True' and 'False' are singletons
> (guaranteed ?) :
>  (not not x) is bool(x)  # should be always True.
> [snip code and results of code]
>   
Consider the following:

 >>> def ok1(x):
return (not not x) is bool(x)

 >>> def ok2(x):
return (not not x) is bool(x) is True

 >>> def ok3(x):
return ok1(x) is True

 >>> def ok4(x):
return ((not not x) is bool(x)) is True

 >>> def ok5(x):
return ((not not x) is bool(x)) and (bool(x) is True)

 >>> for x in [False, True]:
print x,ok1(x), ok2(x), ok3(x), ok4(x), ok5(x)

   
False True False True True False
True True True True True True

Note that ok2(x) and ok5(x) exhibit the same behaviour.

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


Communicating with a DLL under Linux

2007-03-13 Thread Mikael Olofsson
I am interested in peoples experience with communicating with DLLs under 
Linux.

Situation:

I'm an electrical engineer that finds pleasure in using my soldering 
iron from time to time. I also find programming, preferably in Python, 
entertaining. I wouldn't call myself a programmer, though. Now, I may 
have found a hobby project that could give me the pleasure from both 
those worlds. There's this USB development gadget for sale in my 
favourite electronics store, and I sure would like to have something 
like that connected to my lab computer (a fairly new budget computer 
running Kubuntu 6.06).

The gadget costs about 50 Euros. It's not a lot of money, but I would 
not like to buy the thing if there is a substancial risk that I will not 
be able to make it work on that computer. From what I've read on the 
box, it assumes Windows (a number of versions), it includes a DLL to 
communicate with it, and example code in VB (iirc). For the interested, 
here's the gadget:

http://www.elfa.se/elfa-bin/dyndok.pl?lang=en&vat=0&dok=9001.htm

I have been looking at ctypes, and from what I read, I should be able to 
communicate with a DLL by using ctypes. It even sounds fairly easy, as 
long as I know what the DLL is supposed to do. I expect there to be some 
kind of manual for the DLL included in the box. Are DLLs universal, or 
are there different DLLs for Windows and Linux (I'm not a programmer, 
remember)? If the vendor claims that the DLL is for Windows, is it 
reasonable to assume that it can be made to work under Linux, from 
Python, that is? Or is this perhaps completely out of the question?

So, who is willing share their experiences? Share advice? Is this as 
easy as it sounds to me? Any pitfalls around?

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


Re: Communicating with a DLL under Linux

2007-03-14 Thread Mikael Olofsson
Thanks for all the responces, both on and off list.

So, I should forget about the DLL, and if I intend to connect the thing 
to a Linux computer, I'll have to develop the code myself for 
communicating with it over USB. Fair enough. I might even try that.

I've done some surfing since yesterday. Why do I always do that after 
asking stupid questions in public? It turns out that a Nicolas Sutre has 
already ported the thing to Linux:

http://linuxk8055.free.fr/

Velleman links to his solution from their product page

http://www.velleman.be/ot/en/product/view/?id=351346

which might mean something. Nicolas solution is only 250 lines of C 
code. It #includes a usb.h, so I guess a lot of its functionality is 
hidden there. It seems structured enough, so I might be able to find 
some inspiration there.

I guess I have some reading to do before I can decide if I shall do this.

Anyway, thanks once again for the responces.

Not completely in dispair...
/MiO
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about __str__

2007-09-24 Thread Mikael Olofsson
Bruno Desthuilliers wrote:
> def __str__(self):
> return "<%s:%s>" % (self.commiterID_, self.commits_)

I would write that in the following way:

def __str__(self):
return "<%(commiterID_)s:%(commits_)s>" % self.__dict__

More explicit IMHO. And easier to maintain, especially if the string 
would contain several insertions.

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


Re: Yield

2007-01-10 Thread Mikael Olofsson
Mathias Panzenboeck wrote:
> def primes():
>   yield 1
>   yield 2
>   [snip rest of code]
>   

Hmm... 1 is not a prime. See for instance

http://en.wikipedia.org/wiki/Prime_number

The definition given there is "In mathematics , a 
*prime number* (or a *prime*) is a natural number  
that has exactly two (distinct) natural number divisors 
." The important part of the statement is "exactly 
two...divisors", which rules out the number 1.

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


Re: Yield

2007-01-10 Thread Mikael Olofsson


I wrote:
> The definition given there is "In mathematics , a 
> *prime number* (or a *prime*) is a natural number 
>  that has exactly two (distinct) natural number 
> divisors ." The important part of the statement is 
> "exactly two...divisors", which rules out the number 1.

Or should I say: Thunderbird made me write:... Those freakin 
 and  was not visible before I 
posted the thing. &%#&%#

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


Re: Please take me off the list

2007-01-30 Thread Mikael Olofsson
Daniel kavic wrote:
> Sorry to waste email space , but I wish to be off this list because I have 
> tried python and it is too difficult for me.
>   

That's sad. Go to

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

and follow instructions.

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


Re: Convert to binary and convert back to strings

2007-02-23 Thread Mikael Olofsson


Neil Cerutti wrote:
> Woah! You better quadruple it instead.
> How about Double Pig Latin?
> No, wait! Use the feared UDPLUD code.
> You go Ubbi Dubbi to Pig Latin, and then Ubbi Dubbi again.
> Let's see here... Ubububythubububonubpubay
> That's what I call ubububeautubububifubububulbubay.

That looks slightly like the toy language that Swedish kids refer to as 
the robbers language: You double each consonant, and place an o between 
each such double consonant. So, applying that to Python, you would get 
popytothohonon. Actually, one of the largest Swedish telecom companies 
has used this toy language in one of their commercials.

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


Re: newbie question(file-delete trailing comma)

2007-02-27 Thread Mikael Olofsson
kavitha thankaian wrote:
> i get an error when i try to delete in file and rename it as out 
> file,,the error says
> "permission denied".

Perhaps you should give us both the exact code you are running and the
complete traceback of the error. That could make things easier. There
can be numerous reasons for "permission denied".

> actually i need something like following:
>  
> in_file = open('in.txt','w')
> for line in in_file:
> line.strip().strip(',')
>  
> but when i run the above code,i get an error"bad file descriptor"

Of course you do! You are opening the file for writing, but your code
attempts to read the file. Probably, you think that the code would
change the lines in the file itself, which it does not, even if it would
be possible to read from a file opened for writing.

What's wrong with the code that Mohammad posted? Note that you might
need to close out_file in his code.

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


Re: newbie question(file-delete trailing comma)

2007-02-28 Thread Mikael Olofsson
kavitha thankaian wrote:
> my script writes a dictionary to a file.but i need only the values 
> from the dictionary which should be sepearted by a comma,,,so i did as 
> following:
> [snip code that generates the incorrect original file]
> when i execute the above code,my test.txt file has the following:
> a,b,c,d,
> now i need to delete the comma at the end,,,this is my problem,,,

This is the first time you mention that you have control over the 
generation of the original file. Then I suggest that you fix the problem 
before generating the file. For instance, consider the following 
interactive session.

 >>> some={1:'a',2:7,3:'c',4:'d'}
 >>> some
{1: 'a', 2: 7, 3: 'c', 4: 'd'}
 >>> some.values()
['a', 7, 'c', 'd']
 >>> [str(x) for x in some.values()]
['a', '7', 'c', 'd']
 >>> ','.join([str(x) for x in some.values()])
'a,7,c,d'

Then write that to your file instead.

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


Re: Sine Wave Curve Fit Question

2008-01-31 Thread Mikael Olofsson
Helmut Jarausch wrote:
> Your model is  A*sin(omega*t+alpha)  where  A and alpha are sought.
> Let T=(t_1,...,t_N)' and  Y=(y_1,..,y_N)'  your measurements (t_i,y_i)
> ( ' denotes transposition )
> 
> First, A*sin(omega*t+alpha) =
>   A*cos(alpha)*sin(omega*t) + A*sin(alpha)*cos(omega*t) =
>   B*sin(omega*t) + D*cos(omega*t)
> 
> by setting  B=A*cos(alpha)  and  D=A*sin(alpha)
> 
> Once, you have  B and D,  tan(alpha)= D/B   A=sqrt(B^2+D^2)

This is all very true, but the equation tan(alpha)=D/B may fool you. 
This may lead you to believe that alpha=arctan(D/B) is a solution, which 
is not always the case. The point (B,D) may be in any of the four 
quadrants of the plane. Assuming B!=0, the solutions to this equation 
fall into the two classes

 alpha = arctan(D/B) + 2*k*pi

and

 alpha = arctan(D/B) + (2*k+1)*pi,

where k is an integer. The sign of B tells you which class gives you the 
solution. If B is positive, the solutions are those in the first class. 
If B is negative, the solutions are instead those in the second class. 
Whithin the correct class, you may of course choose any alternative.

Then we have the case B=0. Then the sign of D determines alpha. If D is 
positive, we have alpha=pi/2, and if D is negative, we have alpha=-pi/2.

Last if both B and D are zero, any alpha will do.

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


Re: confused about __str__ vs. __repr__

2008-12-18 Thread Mikael Olofsson

Diez B. Roggisch wrote:

Yep. And it's easy enough if you don't care about them being different..

def __repr__(self):
return str(self)


If I ever wanted __str__ and __repr__ to return the same thing, I would 
make them equal:


def __str__(self):
return 'whatever you want'
__repr__ = __str__

That makes it more obvious to me what's going on. As a bonus, it saves 
one method call for every repr call.


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


Re: What happened to NASA at Python? :(

2009-03-12 Thread Mikael Olofsson

s...@pobox.com wrote:

In fact, graphics were added for several organizations.  I believe they will
be chosen randomly.  NASA is still there.


In that case, they must be using the random number generator from 
Dilbert. You know, the one that said 9, 9, 9, 9,...


I, at least, get the same parking lot graphics every time I reload the page.

/MiO

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


Re: Man Bites Python

2009-04-16 Thread Mikael Olofsson

I don't think the guy in question finds it that funny.

Roy Hyunjin Han wrote:

Hahaha!

On Thu, Apr 16, 2009 at 10:27 AM, Aahz  wrote:

http://news.yahoo.com/s/nm/20090415/od_nm/us_python_odd_1/print
--
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Why is this newsgroup different from all other newsgroups?

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


Decorating methods - where do my arguments go?

2009-05-08 Thread Mikael Olofsson

Hi all!

I have long tried to avoid decorators, but now I find myself in a 
situation where I think they can help. I seem to be able to decorate 
functions, but I fail miserably when trying to decorate methods. The 
information I have been able to find on-line focuses on decorating 
functions, and do not mention any special problem regarding methods.


Consider the following example. I start by defining a simple decorator:

>>> class test_decorator(object):
... def __init__(self,func):
... self._func = func
... def __call__(self, *args):
... print 'Decorator:', args
... self._func(*args)

Then I decorate a function:

>>> @test_decorator
... def func(*args):
... print 'Function: ', args

Let's try that:

>>> func(1,2,3)
Decorator: (1, 2, 3)
Function:  (1, 2, 3)

OK! That was what I expected. Let's decorate a method:

>>> class cls(object):
... @test_decorator
... def meth(self,*args):
... print 'Method:   ', args

Then try that:

>>> cls().meth(1,2,3)
Decorator: (1, 2, 3)
Method:(2, 3)

Oops! That's weird. I had expected - or at least wanted - the same 
result as for the function above.


Where did the first argument go? If it was sent to the original method 
meth as the real first argument (self), then why did I not get an exception?


More importantly: How do I write a decorator that does not drop arguments?

I guess it all has to do with the fact that the returned callable isn't 
a method of cls. Is it possible to write a decorator that returns a 
callable that is a method of cls, when used on methods in cls?


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


Re: Decorating methods - where do my arguments go?

2009-05-11 Thread Mikael Olofsson

Peter Otten wrote:
You have to turn your decorator into a descriptor by providing a __get__() 
method. A primitive example:


class test_decorator(object):
def __init__(self,func):
self._func = func
def __call__(self, *args):
print 'Decorator:', args
self._func(self.inst, *args)
def __get__(self, inst, cls):
self.inst = inst
return self


Thanks! Works perfectly for methods, as far as I can see. That's 
perfectly OK, since that is what I was asking for. What I failed to 
include in my original post is that I intend to use the decorator for 
functions as well. The above fails for functions on the second row of 
__call__ with


AttributeError: 'test_decorator' object has no attribute 'inst'

It seems to me like __get__ is not called when decorating a function. I 
guess there's no reasonable value for inst in that case. It might be the 
function itself, but it doesn't make sense to call the function with 
itself as its first argument, when it isn't supposed to be called that way.


George Sakkis decorator function solution seems to work equally well for 
functions and methods. However, I prefer the cleaner encapsulation given 
by a class. Based on those observations, I think I will use the 
following approach:


>>> class test_decorator(object):
... _inst = None
... def __init__(self,func):
... self._func = func
... def __call__(self, *args):
... print 'Decorator:', args
... if self._inst is None:
... print 'We seem to be decorating a function.'
... self._func(*args)
... else:
... print 'We seem to be decorating a method.'
... self._func(self._inst,*args)
... def __get__(self, inst, cls):
... self._inst = inst
... return self
...
>>>
>>> @test_decorator
... def func(*args):
... print 'Function: ', args
...
>>>
>>> func(1,2,3)
Decorator: (1, 2, 3)
We seem to be decorating a function.
Function:  (1, 2, 3)
>>>
>>> class cls(object):
... @test_decorator3
... def meth(self,*args):
... print 'Method:   ', args
...
>>>
>>> cls().meth(1,2,3)
Decorator: (1, 2, 3)
We seem to be decorating a method.
Method:(1, 2, 3)

If there are any drawbacks with this approach that I fail to see, please 
enlighten me.


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


Re: Decorating methods - where do my arguments go?

2009-05-11 Thread Mikael Olofsson

George Sakkis wrote:

Yes, just return an actual function from the decorator instead of a
callable object:

def test_decorator2(func):
def wrapper(*args):
print 'Decorator2:', args
func(*args)
return wrapper


class cls(object):
@test_decorator
def meth(self,*args):
print 'Method:   ', args

@test_decorator2
def meth2(self,*args):
print 'Method2:   ', args


Thanks! This has the merit over Peter's solution that it seems to work 
for both functions and methods. However, as you can see from my answer 
to Peter, I think I will go for a class based approach anyway. Still, 
your answer helped me grasping the concepts.


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


Re: Decorating methods - where do my arguments go?

2009-05-11 Thread Mikael Olofsson

Duncan Booth wrote:

The __get__ method should be returning a new object, NOT modifying the 
state of the decorator. As written it will break badly and unexpectedly 
in a variety of situations:


[snip good examples of things going bad]


Ouch! So, does that mean that George's solution based on a function is 
the way to go, or does that mean that my __call__ should analyze the 
passed callable?


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


Re: Decorating methods - where do my arguments go?

2009-05-12 Thread Mikael Olofsson

Peter Otten wrote:
I usually use decorator functions, but I think the following should work, 
too:


class deco(object):
def __init__(self, func):
self._func = func
def __call__(self, *args):
print "Decorator:", args
self._func(*args)
def __get__(self, *args):
return deco(self._func.__get__(*args))


This looks like a winner to me. It is elegant, works for functions as 
well as for methods, and does not mess with the internals of the 
decorator which avoids the problems that Duncan pointed out.


Thanks Peter, and thanks everyone else that chimed in and contributed.

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


Re: Decorating methods - where do my arguments go?

2009-05-12 Thread Mikael Olofsson

Michele Simionato wrote:
> Still it turns something which is a function into an object and
> you lose the docstring and the signature. pydoc will not be too
> happy with this approach.

Duncan Booth wrote:

I don't know why Mikael wants to use a class rather than a function
but if he wants to save state between calls this isn't going to help.


I've never used decorators before, and that's the main reason for my 
confusion. I have found myself in a situation where I think that 
decorators is the way to go. So I tried to find information about how to 
write them the usual way: Googling and browsing documentation. I found 
examples using both functions and classes, but not much explanation of 
what's going on, especially not in the class case. I didn't find any 
arguments for favouring any of those alternatives. Actually, most 
examples I found did not even include the definition of the actual 
decorator or any information about where they might come from, only the 
@-row.


Based on the above observations, I assumed that both alternatives were 
equally possible. The first answers I got here also led me to believe 
that that was the case. My understanding is that in most cases, you can 
use a callable object instead of a function with little or no practical 
difference, except the syntax of its definition. In my eyes, a class 
definition looks nicer and is more readable than a nested function. 
Therefore, I tend to define a class with a __call__ method and helper 
methods instead of nested functions, if I find the need.


Practicality beats purity, and it seem like using a class for decoration 
is a lot more hassle than using a function. I fold.


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


Re: passing *args "recursively"

2008-05-13 Thread Mikael Olofsson

Guillermo wrote:

This must be very basic, but how'd you pass the same *args several
levels deep?

def func2(*args)
print args # ((1, 2, 3),)
# i want this to output (1, 2, 3) as func1!
# there must be some better way than args[0]?

def func1(*args):
print args # (1, 2, 3)
func2(args)

func1(1,2,3)


func2(*args)

Thats all. See 
http://docs.python.org/tut/node6.html#SECTION00674


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


Re: passing *args "recursively"

2008-05-13 Thread Mikael Olofsson

Guillermo wrote:

This must be very basic, but how'd you pass the same *args several
levels deep?

def func2(*args)
print args # ((1, 2, 3),)
# i want this to output (1, 2, 3) as func1!
# there must be some better way than args[0]?

def func1(*args):
print args # (1, 2, 3)
func2(args)

func1(1,2,3)


Me, myself and I wrote:

func2(*args)

Thats all. See 
http://docs.python.org/tut/node6.html#SECTION00674


That was a bit unclear. You should use func2(*args) when you call the 
function.


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


Re: Rounding a number to nearest even

2008-04-11 Thread Mikael Olofsson
[EMAIL PROTECTED] commented about rounding towards even numbers
from mid-way between integers as opposed to for instance always rounding 
up in those cases:
> Strange request though, why do you need it that way, because 2.5 is
> CLOSER to 3 than to 2...

That's exactly how I was taught to do rounding in what-ever low-level 
class it was. The idea is to avoid a bias, which assumes that the 
original values are already quantized. Assume that we have values 
quantized to one decimal only, and assume that all values of this 
decimal are equally likely. Also assume that the integer part of our 
numbers are equally likely to be even or odd. Then the average rounding 
error when rounding to integers will be 0.05 if you always round up when 
the decimal is 5. If you round towards an even number instead when the 
decimal is 5, then you will round up half of those times, and round down 
the other half, and the average rounding error will be 0. That's the 
idea. Of course you could argue that it would be even more fair to make 
the choice based on the tossing of a fair coin.

Note that if you do not have quantized values and assuming that the 
fraction part is evenly distributed between 0 and 1, than this whole 
argument is moot. The probability of getting exactly 0.5 is zero in that 
case, just as the probability of getting any other specified number is zero.

That said, measurements are in practice always quantized, and rounding 
towards an even number when mid-way between avoids an average error of 
half the original precision.

As a side-note: The the smallest coin in Swedish currency SEK is 0.50, 
but prices in stores are given with two decimals, i.e. with precision 
0.01. But what if your goods add up to 12.34? The standard in Swedish 
stores, after adding the prices of your goods, is to round the number to 
the nearest whole or half SEK, which means that decimals 25 and 75 are 
mid-way between. In those cases the rounding is usually done to the 
nearest whole SEK, which is based on precicely the above reasoning. If 
they did not do that, I could argue that they are stealing on average 
0.005 SEK from me every time I go to the store. Well... I could live 
with that, since 0.005 SEK is a ridiculously small amount, and even if I 
make thousands of such transactions per year, it still sums up to a 
neglectable amount.

Another side-note: My 12-year old son is now being taught to always 
round up from mid-way between. Yet another example of the degradation of 
maths in schools.

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


Re: Negative integers

2008-08-21 Thread Mikael Olofsson

Derek Martin wrote:
Zero is a problem, no matter how you slice it.  


I definitely agree with that. Depends on the the real problem that is 
behind the OP:s question.



Zero can be considered
positive or negative (mathematically, 0 = -0).


I've read quite a few articles written by mathematicians and 
mathematically oriented engineers, and my impression is that most of 
them, and therefore me included, use those words with the following meaning:


Positive: >0
Negative: <0

When zero is to be included, the following terms are used:

Non-negative: >=0
Non-positive: <=0

Using this convention, zero is neither positive nor negative. Wikipedia 
seems to agree with that:


http://en.wikipedia.org/wiki/Positive_number

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


Re: implementation of "complex" type

2006-03-09 Thread Mikael Olofsson
Russ wrote:
x = complex(4)
y = x
y *= 2
print x, y
> 
> (4+0j) (8+0j)
> 
> But when I tried the same thing with my own class in place of
> "complex" above, I found that both x and y were doubled. I'd like to
> make my class behave like the "complex" class. Can someone tell me the
> trick? Also, where can I find the code for for the "complex" class? I
> hope it's written in Python! Thanks.

Have your __imul__ and such return new objects, and not perform in-place 
modification if you do not want x and y to refer to the same object 
after y*=2.

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


Re: accesibility of the namespace

2006-03-09 Thread Mikael Olofsson
Petr Jakes wrote:
> Ops. My keyboard (fingers) was faster than my mind :(
> So
> There is more than one "run-time changed variable" in the dictionary
> and not all strings in the dictionary are formatted using % operator.
> Example:
> lcd={
> 2:{2:(("Enter you choice"),("Your kredit= %3d" % (kredit)))},
> 4:{2:(("Your choice: %2s" % (keyboard)),("%-20s" % (actKeyboard)))}}
> 
> I do not know which variable(s) to use for the % operator in the time
> of the call of the value (% formatted string) from the dictionary.
> 
> This is also the reason why the variable names are stored in the
> dictionary with the strings.
> 
> Any other suggestions?

So, use something like

 >>> lcd={
2:{2:("Enter you choice","Your kredit= %(kredit)3d")},
4:{2:("Your choice: %(keyboard)2s" ,"%(actKeyboard)-20s")}}
 >>> kredit = 7
 >>> keyboard = 'aa'
 >>> actKeyboard = 7654
 >>> lcd[2][2][-1] % vars()
'Your kredit=   7'
 >>> lcd[2][2][0] % vars()
'Enter you choice'
 >>> lcd[4][2][0] % vars()
'Your choice: aa'
 >>> lcd[4][2][1] % vars()
'7654'
 >>>

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