[Tutor] datetime, time zones, and ISO time

2010-02-17 Thread David Perlman
I have been really scratching my head over this, it seems like there  
*should* be a nice easy way to do what I want but I can't find it for  
the life of me.


What I would like to do would be something like this:

>>> datetime.datetime.now().isoformat()
'2010-02-17T12:13:17.913260-06:00'

But what actually happens is this:
'2010-02-17T12:13:17.913260'

I need to keep track of the time zone because I'm working with Google  
Calendar's query APIs, and it interprets all times as GMT unless you  
specify the time zone, which means my search results are wrong.   
Anyway, I was thinking I could get around it with something like:


now=datetime.datetime.now()
offset=datetime.datetime.utcoffset()
[somehow add the offset info into the "now" datetime object]
now.isoformat()

But a) I don't know how to stick the offset info into a datetime  
object, and the documentation doesn't seem to say anything about this;  
and b) the offset line doesn't work anyway:


>>> datetime.datetime.utcoffset()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: descriptor 'utcoffset' of 'datetime.datetime' object needs  
an argument


I think there's a combination of problems here, involving me not  
understanding something fundamental about datetime objects, and also  
involving problems with the documentation (there are a whole lot of  
places where the optional arguments to the methods are left off of the  
syntax, for example.)


Can anyone help sort me out here?  In particular, is there a really  
straightforward way to do what I'm looking for?


One more general kind of confusion that this has raised for me is that  
it seems that in the datetime documentation (and possibly other places  
as well) there is an unexplained distinction between methods which can  
be used to give you new information, and methods which only can tell  
you something about the instance they are invoked on.  For example,  
this works the way I feel like it ought to:


>>> datetime.datetime.now()
datetime.datetime(2010, 2, 17, 12, 42, 30, 520792)

But this doesn't work at all:
>>> datetime.datetime.utcoffset()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: descriptor 'utcoffset' of 'datetime.datetime' object needs  
an argument


And I haven't been able to find another method instead of utcoffset()  
that will give me what I want.


Thanks very much to anyone who can illuminate my darkness on this  
matter.  :)


--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



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


Re: [Tutor] datetime, time zones, and ISO time

2010-02-17 Thread David Perlman
Yeah, I got this part.  The thing that's hanging me up is that there  
doesn't seem to be any way to get a tzinfo instance that contains the  
current local time zone information.  You can do time.timezone to get  
the seconds from UTC, but there doesn't seem to be any way to convert  
that into a tzinfo!  I would be perfectly satisfied with this:


tz=offset_to_tzinfo(time.timezone) # or whatever
aware_now=datetime.datetime.now(tz)
print aware_now.isoformat()

I'm pretty sure that would give me what I want, but there doesn't seem  
to be any way to do step one without subclassing tzinfo.  This makes  
me feel like I MUST be missing something obvious, because it shouldn't  
require so much coding just to find out what the current local time  
and timezone is!



On Feb 17, 2010, at 1:42 PM, William Witteman wrote:


On Wed, Feb 17, 2010 at 12:44:02PM -0600, David Perlman wrote:

I have been really scratching my head over this, it seems like there
*should* be a nice easy way to do what I want but I can't find it for
the life of me.

...

But a) I don't know how to stick the offset info into a datetime
object, and the documentation doesn't seem to say anything about
this; and b) the offset line doesn't work anyway:


I think that you need to push in a tzinfo object, rather than a value:

http://docs.python.org/library/datetime.html#datetime.tzinfo

I get that from here:

For applications requiring more, datetime  and time objects have an
optional time zone information member, tzinfo, that can contain an
instance of a subclass of the abstract tzinfo class. These tzinfo
objects capture information about the offset from UTC time, the time
zone name, and whether Daylight Saving Time is in effect. Note that no
concrete tzinfo classes are supplied by the datetime module.  
Supporting

timezones at whatever level of detail is required is up to the
application. The rules for time adjustment across the world are more
political than rational, and there is no standard suitable for every
application.[1]

I suspect that it'll take some fooling around to see how it works  
though

- use the interpreter or ipython to test things out.

[1] http://docs.python.org/library/datetime.html
--

yours,

William

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


--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



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


Re: [Tutor] datetime, time zones, and ISO time

2010-02-17 Thread David Perlman
But this doesn't help, because then you still don't know whether it's  
dst or not.  You then would have to jump through whatever convolutions  
to do that calculation.


All I want to know is the *current* offset between local time and  
utc.  I know the system has this information already; it doesn't  
require any kind of fancy calculations about global politics or  
anything.



On Feb 17, 2010, at 3:12 PM, Kent Johnson wrote:

On Wed, Feb 17, 2010 at 3:48 PM, David Perlman   
wrote:
Surely there is a way to simply print out the local time, date and  
time zone
without needing to write your own class...  I can't believe this is  
the only

way...

Here's why I don't believe it.  Both the datetime and time modules  
provide
both functions for returning the current local time, and the  
current utc
time.  So, assuming that those functions are trustworthy, it *must*  
be true
that the OS always knows the current offset from utc time.  So why  
is there
no straightforward way to get that offset in python?  I mean, I can  
do this:


time.timezone gives the offset for standard time.


--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



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


Re: [Tutor] datetime, time zones, and ISO time

2010-02-17 Thread David Perlman

OK, here's a function that does precisely what I want:

def tzDelta():
  """by whatever means necessary, return the current offset of the  
local time from utc."""

  s=time.time()
  t,u=time.localtime(s),time.gmtime(s)
  osec=3600*(t[3]-u[3]) + 60*(t[4]-u[4]) + (t[5]-u[5])
  return datetime.timedelta(seconds=osec)


As far as I can tell, this should always work.  So wouldn't it be nice  
if there were a less convoluted way to get this??



On Feb 17, 2010, at 3:12 PM, Kent Johnson wrote:

On Wed, Feb 17, 2010 at 3:48 PM, David Perlman   
wrote:
Surely there is a way to simply print out the local time, date and  
time zone
without needing to write your own class...  I can't believe this is  
the only

way...

Here's why I don't believe it.  Both the datetime and time modules  
provide
both functions for returning the current local time, and the  
current utc
time.  So, assuming that those functions are trustworthy, it *must*  
be true
that the OS always knows the current offset from utc time.  So why  
is there
no straightforward way to get that offset in python?  I mean, I can  
do this:


time.timezone gives the offset for standard time.

Kent




datetime.datetime.now()-datetime.datetime.utcnow()

datetime.timedelta(-1, 64799, 87)

But then, of course, it's off by a few fractions of a microsecond.   
This

works:


time.localtime()[3]-time.gmtime()[3]

-6

But doesn't that seem like a ridiculous hack, well outside of the  
spirit of
the zen of python?  Shouldn't there be one obvious right way to do  
this?


Yes, I know that as William sent, the documentation points out that  
the
rules the world over are complicated and irrational.  Nonetheless,  
it is
implicit in the existing definitions that the system *knows* the  
current

offset, even if it doesn't know the whole set of rules...


On Feb 17, 2010, at 2:26 PM, Kent Johnson wrote:

On Wed, Feb 17, 2010 at 3:12 PM, David Perlman   
wrote:


Yeah, I got this part.  The thing that's hanging me up is that  
there

doesn't
seem to be any way to get a tzinfo instance that contains the  
current

local
time zone information.  You can do time.timezone to get the  
seconds from
UTC, but there doesn't seem to be any way to convert that into a  
tzinfo!

 I
would be perfectly satisfied with this:

tz=offset_to_tzinfo(time.timezone) # or whatever
aware_now=datetime.datetime.now(tz)
print aware_now.isoformat()

I'm pretty sure that would give me what I want, but there doesn't  
seem to

be
any way to do step one without subclassing tzinfo.  This makes me  
feel

like
I MUST be missing something obvious, because it shouldn't require  
so much
coding just to find out what the current local time and timezone  
is!


The docs make it clear that you do have to subclass tzinfo, that no
implementations are provided.
It sounds like you want the LocalTimezone class in the examples at  
the

bottom of this section - "A class capturing the platform's idea of
local time":
http://docs.python.org/library/datetime.html#tzinfo-objects

Kent


--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard






--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



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


Re: [Tutor] datetime, time zones, and ISO time

2010-02-17 Thread David Perlman

On Feb 17, 2010, at 4:17 PM, Sander Sweers wrote:


On 17 February 2010 22:37, David Perlman  wrote:
As far as I can tell, this should always work.  So wouldn't it be  
nice if

there were a less convoluted way to get this??


There is pytz [1] which should provide a simpler way to manage
timezone info in python.


Well, this is actually more complicated, not simpler.  The description  
says:


pytz brings the Olson tz database into Python. This library allows  
accurate and cross platform timezone calculations using Python 2.3 or  
higher. It also solves the issue of ambiguous times at the end of  
daylight savings, which you can read more about in the Python Library  
Reference (datetime.tzinfo).


I don't want to deal with any of that stuff, I just want to know the  
actual current offset between local time and UTC.  I don't care what  
the offset is in Nepal; I don't care what the offset will be come  
summertime; I don't care about anything in the Olson tz database.  I  
just want something to tell me the current offset, right here, right  
now, on my own computer.


Anyway, I already wrote a function to calculate it, so it's a done  
deal.  At this point I'm just really surprised that I had to...


For completeness, here's what I came up with.  The format function was  
necessary because Google calendar queries require the time zone to be  
represented in the string like:

2010-03-01T21:00:00.000-06:00
However the isoformat() methods in python instead give something like:
2010-03-01T21:00:00.000-0600
which gives a server error if you try to send it to Google.   
Unfortunately, and also bizarrely, even the strftime() doesn't provide  
any way to generate the format Google demands, so I had to also write  
a function to do the formatting.


  def tzDeltaForm(self, tzd=None):
"""return the tzdelta in the format Google wants it, such as  
-06:00"""

if not tzd: tzd=self.tzDelta()
if tzd < 0:
  sign = -1
  tzd = -tzd
else:
  sign = 1
h = sign * tzd // 3600
m = (tzd % 3600) // 60
form = '%+03d:%02d' % (h,m)
return form


  def tzDelta(self):
"""by whatever means necessary, return the current offset of the  
local time from utc."""

s=time.time()
t,u=time.localtime(s),time.gmtime(s)
osec=3600*(t[3]-u[3]) + 60*(t[4]-u[4]) + (t[5]-u[5])
#return datetime.timedelta(seconds=osec)
return osec

OK, I hope that is helpful to someone else someday, because it has  
been an astonishing amount of pain to accomplish something seemingly  
so simple...  Thanks to everyone for the input, every bit of it helped  
guide me along.  :)




--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



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


[Tutor] list of dicts <-> dict of lists?

2010-05-27 Thread David Perlman
Using the csv.DictReader and csv.DictWriter lets you read and write  
lists of dictionaries from files containing tabular data.  I have a  
system that naturally generates tabular data in the form of a  
dictionary of lists: the dictionary key is the name of the column, and  
then the value is a list which contains the data for that column.   
Sort of like a spreadsheet.  I would like to use csv.DictWriter to  
write out this data but that requires a list of dicts.


I can convert the dict of lists to a list of dicts, and thus make it  
compatible with csv.DictWriter, with the following ugly comprehensions:


>>> y
{'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}
>>> [dict([(i,y[i][j]) for i in y.keys()]) for j in  
range(len(y[y.keys()[0]]))]
[{'a': 1, 'c': 7, 'b': 4}, {'a': 2, 'c': 8, 'b': 5}, {'a': 3, 'c': 9,  
'b': 6}]


...but I'm wondering if anyone knows of a more elegant way, perhaps  
something built-in suited for this purpose...


I am aware that any solution will only work if the lists in the dict  
are all the same length.  :)


Thanks!


--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



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


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-28 Thread David Perlman
Aha, now this is the clever solution that I didn't find "outside the  
box".  :)


On May 28, 2010, at 2:33 AM, Peter Otten wrote:


I think it's simpler and therefore more appropriate to use a normal
csv.writer here:


import csv
import sys
data = {'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}
writer = csv.writer(sys.stdout)
writer.writerow(data.keys())

a,c,b

writer.writerows(zip(*data.values()))

1,7,4
2,8,5
3,9,6

Peter


--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



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


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-28 Thread David Perlman
Oh, except one problem: the csv.DictWriter lets you tell it what order  
you want the columns output in.  With your version, they just show up  
in whatever order Python wants them.


On May 28, 2010, at 2:33 AM, Peter Otten wrote:


I think it's simpler and therefore more appropriate to use a normal
csv.writer here:


import csv
import sys
data = {'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}
writer = csv.writer(sys.stdout)
writer.writerow(data.keys())

a,c,b

writer.writerows(zip(*data.values()))

1,7,4
2,8,5
3,9,6


--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



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


[Tutor] Processing a string of bytes

2009-09-03 Thread David Perlman
I have successfully used the builtin "wave" module to read an audio  
file in as a string of bytes:


>>> x=wave.open('DaCWL.wav','rb')
>>> x.getparams()
(1, 2, 44100, 15440, 'NONE', 'not compressed')
>>> samp=x.readframes(15440)
>>> type(samp)


The x.getparams() indicates that there is one audio channel, 2 bytes  
per sample, 44100 sampling rate, and 15440 samples in the file.


What I would like to know is, what is the most elegant and (dare I say  
it) pythonic way to do some processing on the resulting string of  
bytes, which represents a sequence of two-byte signed integers?  The  
goal is to normalize the file, by taking the root-mean-square and then  
scaling every sample accordingly.  So I only need to do simple  
arithmetic on the sample values.


The obvious thing to do is to use a loop to get two bytes at a time,  
convert them to int, and work on the resulting list of ints.  However  
this seems kind of inelegant, and wasteful of space, since python ints  
are way more than two bytes.  Also I'm not sure if there's a  
convenient built-in way to do that conversion.


So, in summary, I would be interested in either of two things:
1. advice on how to do arithmetic on the string of bytes without  
converting it to a list of ints first, or
2. advice on how to convert it to a list of ints, and then back to a  
string of bytes.


Thanks very much!

--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



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


[Tutor] Poorly understood error involving class inheritance

2009-09-10 Thread David Perlman

I'm not sure why I'm getting an error at the end here:

>>> class dummy:
... def __init__(self,dur=0):
... self.dur=dur
...
>>> z=dummy(3)
>>> z.dur
3
>>> z=dummy(dur=3)
>>> z.dur
3

That worked fine, of course.

>>> class dummy2(str):
... def __init__(self,dur=0):
... self.dur=dur
...
>>> z=dummy2(3)
>>> z.dur
3

So far so good.  But:

>>> z=dummy2(dur=3)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'dur' is an invalid keyword argument for this function
>>>

Why doesn't that last bit work?  I'm not sure where to begin to look  
this up.

Thanks!

--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



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


Re: [Tutor] Poorly understood error involving class inheritance

2009-09-10 Thread David Perlman

Well, here's what I am really doing:

class oneStim(str):
def __init__(self, time, mods=[], dur=None, format='%1.2f'):
self.time=time
self.mods=mods
self.dur=dur
self.format=format

def __cmp__(self,other):
return cmp(self.time,other.time)

def __repr__(self):
timestr=self.format % self.time
if self.mods == []:
modstr=''
else:
modstr = '*' + ','.join(self.format % i for i in self.mods)
if self.dur == None:
durstr = ''
else:
durstr = ':' + (self.format % self.dur)
return timestr + modstr + durstr

def __len__(self):
return len(self.__repr__())


The purpose of this is to make an object that holds a collection of  
numbers and represents them as a specifically formatted string.  I  
want to be able to do something like:


>>> z=oneStim(22.5678)
>>> z.dur=10
>>> z
22.57:10.00
>>> len(z)
11
>>> z.rjust(20)
' 22.5678'

Note that that doesn't work either.  It works fine like this, though:
>>> z
22.57:10.00
>>> str(z).rjust(20)
' 22.57:10.00'

I can work with that just fine, but I am curious to understand what's  
going on under the hood that makes it fail when subclassed from str...



On Sep 10, 2009, at 3:42 PM, Serdar Tumgoren wrote:


class dummy2(str):

... def __init__(self,dur=0):
... self.dur=dur
...

z=dummy2(3)
z.dur

3

So far so good.  But:


z=dummy2(dur=3)

Traceback (most recent call last):
 File "", line 1, in 
TypeError: 'dur' is an invalid keyword argument for this function




I think you're problem may stem from the fact that you subclassed the
string type and then tried to pass in an integer.


class Dummy2(int):

... def __init__(self, dur=0):
... self.dur = dur
...

z = Dummy2(3)
z.dur

3

When you sub "int" for "str", it seems to work. Is there a reason
you're not just subclassing "object"? I believe doing so would give
you the best of both worlds.


--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



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


Re: [Tutor] Poorly understood error involving class inheritance

2009-09-10 Thread David Perlman

Yeah, this seems to be the best answer in this situation.  :)

On Sep 10, 2009, at 4:17 PM, Kent Johnson wrote:


I would skip the cleverness of trying to subclass string. You can use
str(z).rjust(20) as above, or use string formatting:
 '%20s' % z


--
-dave
Unfortunately, as soon as they graduate, our people return
to a world driven by a tool that is the antithesis of thinking:
PowerPoint. Make no mistake, PowerPoint is not a neutral tool —
it is actively hostile to thoughtful decision-making. It has
fundamentally changed our culture by altering the expectations
of who makes decisions, what decisions they make and how
they make them.  -Colonel T. X. Hammes, USMC

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


Re: [Tutor] Poorly understood error involving class inheritance

2009-10-05 Thread David Perlman
OK, I thought I had this one fixed but it was weirder than I thought.   
I think I understand what's going on, but I wanted to check with the  
experts here.


I have the following class definition, which does not subclass anything:

class oneStim:
def __init__(self, time, mods=[], dur=None, format='%1.2f'):
self.time=time
self.mods=mods
self.dur=dur
self.format=format

def __cmp__(self,other):
return cmp(self.time,other.time)

def __repr__(self):
timestr=self.format % self.time
if self.mods == []:
modstr=''
else:
modstr = '*' + ','.join(self.format % i for i in self.mods)
if self.dur == None:
durstr = ''
else:
durstr = ':' + (self.format % self.dur)
return timestr + modstr + durstr

def __len__(self):
return len(self.__repr__())


>>> a=oneStim(40)
>>> a
40.00
>>> a.mods.append(3)
>>> a
40.00*3.00
>>> a.dur=10
>>> a
40.00*3.00:10.00
>>> a.mods.append(1)
>>> a
40.00*3.00,1.00:10.00

So far so good, that's exactly what it's supposed to do.  But now look:

>>> b=oneStim(50)
>>> b
50.00*3.00,1.00

The mods that were added to the first instance of oneStim also appear  
in the second, newly created instance!


It appears that what is happening here is that the __init__() method  
is being parsed by the interpreter once at initial run, and at that  
time the statement "mods=[]" is being parsed, which means that the []  
object is being instantiated once there at the beginning.  So every  
instantiation of class oneStim ends up sharing a reference to the same  
list object, instead of each one having its own.


I fixed this by changing it to "mods=None" and then setting it in the  
body of the __init__ method.  Works fine now.


My question is, is this just a quirky misbehavior, or is there a  
principled reason why the code I have shown above only instantiates  
the empty list in the arguments once?


Thanks for any insight.  As I said, I got it to work fine now, so this  
isn't critical, but I'm curious to understand why things work the way  
they do.  :)


--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



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


[Tutor] Methods that return instances of their own class?

2009-10-15 Thread David Perlman
I'm trying to figure out how to define a class so that its instances  
have a method that return a different object of the same class.


In particular, I'm trying to run a simple prisoner's dilemma game, and  
I want to make a "game" object that has a method which returns the  
"game" object with the payoffs reversed; that is, the payoff matrix  
from the other player's point of view.  Basically a kind of transpose  
which is specific to this application.


class Payoffs(list):
def __init__(self, value=None):
list.__init__(self)
if value==None: # use a default prisoner's dilemma
value=[[(3,3),(0,5)],
   [(5,0),(1,1)]]
self.extend(value)

def __repr__(self):
l1="Your Choice:   CooperateDefect\n"
l2="My choice:   -\n"
l3="Cooperate| (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[0] 
[0][0], self[0][0][1], self[0][1][0], self[0][1][1])

l4="  --- \n"
l5="Defect   | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[1] 
[0][0], self[1][0][1], self[1][1][0], self[1][1][1])

l6=" -\n"
return l1+l2+l3+l4+l5+l6

def transpose(self):

And that's where I'm at.  How can I have the transpose method return  
another Payoffs object?  Here's the beginning of it:


def transpose(self):
trans=[[(self[0][0][1],self[0][0][0]), (self[1][0][1],self[1] 
[0][0])],
   [(self[0][1][1],self[0][1][0]), (self[1][1][1],self[1] 
[1][0])]]


But now "trans" is type list, not type Payoffs.  I don't know how to  
get it into a Payoffs object so that the transpose will have my other  
new methods.



Thanks very much.  I searched for answers but I'm not sure what this  
would be called, which made it hard to find.


--
-dave
Unfortunately, as soon as they graduate, our people return
to a world driven by a tool that is the antithesis of thinking:
PowerPoint. Make no mistake, PowerPoint is not a neutral tool —
it is actively hostile to thoughtful decision-making. It has
fundamentally changed our culture by altering the expectations
of who makes decisions, what decisions they make and how
they make them.  -Colonel T. X. Hammes, USMC

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


Re: [Tutor] Methods that return instances of their own class?

2009-10-15 Thread David Perlman
Oh my goodness, it really is that easy!  I guess I assumed that was  
too simple to work.  Silly me.  Thanks Andre!


On Oct 15, 2009, at 10:31 AM, Andre Engels wrote:

On Thu, Oct 15, 2009 at 5:14 PM, David Perlman   
wrote:
I'm trying to figure out how to define a class so that its  
instances have a

method that return a different object of the same class.

In particular, I'm trying to run a simple prisoner's dilemma game,  
and I
want to make a "game" object that has a method which returns the  
"game"
object with the payoffs reversed; that is, the payoff matrix from  
the other
player's point of view.  Basically a kind of transpose which is  
specific to

this application.

class Payoffs(list):
   def __init__(self, value=None):
   list.__init__(self)
   if value==None: # use a default prisoner's dilemma
   value=[[(3,3),(0,5)],
  [(5,0),(1,1)]]
   self.extend(value)

   def __repr__(self):
   l1="Your Choice:   CooperateDefect\n"
   l2="My choice:   -\n"
   l3="Cooperate| (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[0] 
[0][0],

self[0][0][1], self[0][1][0], self[0][1][1])
   l4="  --- \n"
   l5="Defect   | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[1] 
[0][0],

self[1][0][1], self[1][1][0], self[1][1][1])
   l6=" -\n"
   return l1+l2+l3+l4+l5+l6

   def transpose(self):

And that's where I'm at.  How can I have the transpose method  
return another

Payoffs object?  Here's the beginning of it:

   def transpose(self):
   trans=[[(self[0][0][1],self[0][0][0]),
(self[1][0][1],self[1][0][0])],
  [(self[0][1][1],self[0][1][0]),
(self[1][1][1],self[1][1][0])]]

But now "trans" is type list, not type Payoffs.  I don't know how  
to get it
into a Payoffs object so that the transpose will have my other new  
methods.



Thanks very much.  I searched for answers but I'm not sure what  
this would

be called, which made it hard to find.


I may be thinking too simple, but isn't this just:

def transpose(self):
trans=[[(self[0][0][1],self[0][0][0]), (self[1][0][1],self[1][0] 
[0])],
  [(self[0][1][1],self[0][1][0]), (self[1][1][1],self[1] 
[1][0])]]

return Payoffs(trans)


--
André Engels, andreeng...@gmail.com


--
-dave
Unfortunately, as soon as they graduate, our people return
to a world driven by a tool that is the antithesis of thinking:
PowerPoint. Make no mistake, PowerPoint is not a neutral tool —
it is actively hostile to thoughtful decision-making. It has
fundamentally changed our culture by altering the expectations
of who makes decisions, what decisions they make and how
they make them.  -Colonel T. X. Hammes, USMC

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


Re: [Tutor] Methods that return instances of their own class?

2009-10-15 Thread David Perlman
Maybe there's a prettier way to do this, but I did it explicitly like  
this because the "transpose" I needed was specific to the structure of  
the game payoff matrix; it isn't a normal mathematical transpose.  I  
agree that it's hard to read but I'm not sure the specific needs of  
this application allow a cleaner solution.  I'd love to hear it if  
there was one though!


On Oct 15, 2009, at 12:33 PM, Che M wrote:


> def transpose(self):
>
> And that's where I'm at. How can I have the transpose method return
> another Payoffs object? Here's the beginning of it:
>
> def transpose(self):
> trans=[[(self[0][0][1],self[0][0][0]), (self[1][0][1],self[1]
> [0][0])],
> [(self[0][1][1],self[0][1][0]), (self[1][1][1],self[1]
> [1][0])]]

Did this have to be hardcoded like this, or is there a more
Pythonic way to transpose the payoff list?  Maybe it needs
to look like this, but this does not strike me as very readable.


--
-dave
Unfortunately, as soon as they graduate, our people return
to a world driven by a tool that is the antithesis of thinking:
PowerPoint. Make no mistake, PowerPoint is not a neutral tool —
it is actively hostile to thoughtful decision-making. It has
fundamentally changed our culture by altering the expectations
of who makes decisions, what decisions they make and how
they make them.  -Colonel T. X. Hammes, USMC

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


[Tutor] subclass question

2009-12-19 Thread David Perlman

If I make a subclass of a built-in class, like this:

class mylist(list):
def __init__(self):
list.__init__(self)

Then it is valid for me to do this:

>>> x=mylist()
>>> x.hello=3
>>>

But I can't do this:

>>> y=list()
>>> y.hello=3
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'list' object has no attribute 'hello'
>>>

What is it that is special about built-in classes that prevents you  
from adding methods or, uh, whatever the generic term is for sub- 
variables?  Is there a way to make your own classes restricted like  
that?


OK thanks!


--
-dave
Unfortunately, as soon as they graduate, our people return
to a world driven by a tool that is the antithesis of thinking:
PowerPoint. Make no mistake, PowerPoint is not a neutral tool —
it is actively hostile to thoughtful decision-making. It has
fundamentally changed our culture by altering the expectations
of who makes decisions, what decisions they make and how
they make them.  -Colonel T. X. Hammes, USMC

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


Re: [Tutor] Bundle help!

2007-07-09 Thread David Perlman
I think what you want to do is start from the beginning with two  
separate lists, sort each one however you want, and then either join  
them with zip() or simply reference them as (list1[n], list2[n]).

I believe there's also a way to use zip() to separate your list of  
tuples into separate lists, but I don't know how off the top of my  
head.  You can find out if you follow these instructions though:

Go to
http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&group=comp.lang.py
enter 'zip inverse', and check search Python only.


On Jul 8, 2007, at 6:41 PM, Sara Johnson wrote:

> How would I do that so I wind up with both lists?  I have two lists  
> now, but if I try and reorder them they just reverse in  
> alphabetical order without affecting the second value (the number).
>

--
-dave
All I ask is that the kind of unsolvable that it turns out to be has
respectable precedents.  -Jerry Fodor


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


Re: [Tutor] Bundle help!

2007-07-09 Thread David Perlman
Maybe this reference will help:
http://xahlee.org/perl-python/sort_list.html
Just the first part of the discussion there.

On Jul 9, 2007, at 9:54 AM, Sara Johnson wrote:

> Sorry to be so confusing.  Just realized a dumb mistake I made.  It  
> doesn't need to be resorted alphabetically and numerically.  I need  
> one list alphabetical and one numerical.
>
>
>  (Alphabetical) List 1, [('Fred', 20), ('Joe', 90), ('Kent', 50),  
> ('Sara', 80)]
>
> (Numerical) List 2,  [('Fred', 20), ('Kent', 50), ('Sara', 80)  
> ('Joe', 90)]
>
>
> It looks like these are appended together, but to re-sort, how do I  
> (not sure if this is a word) "unappend" them?
>

--
-dave
All I ask is that the kind of unsolvable that it turns out to be has
respectable precedents.  -Jerry Fodor


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


Re: [Tutor] Regex Ordering

2007-07-23 Thread David Perlman
Then maybe you could write a regex that matches every regex that does  
not match itself.

ha!  sorry, couldn't resist.

On Jul 23, 2007, at 11:29 AM, Bill Campbell wrote:

> On Mon, Jul 23, 2007, James Hartley wrote:
>> On 7/23/07, Shidan <[EMAIL PROTECTED]> wrote:
>>> I'm looking for a Python module that provides methods for ordering
>>> regexes based on
>>> how general they are ( how much they match). Do I have to write it
>>
>> Your question is relative.  Classifying which regular expression is
>> more general depends upon the other regular expressions used in
>> comparison along with the specific input.  As you change input &
>> regular expressions, the ordering will change.
>
> As a first cut, one might sort the regular expression strings in
> reverse order such that the longer strings are tested first.
>
> Bill
> --
> INTERNET:   [EMAIL PROTECTED]  Bill Campbell; Celestial Software LLC
> URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
> FAX:(206) 232-9186  Mercer Island, WA 98040-0820; (206)  
> 236-1676
>
> Virtually everything is under federal control nowadays except the
> federal budget.
> -- Herman E. Talmadge, 1975
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

--
-dave
All I ask is that the kind of unsolvable that it turns out to be has
respectable precedents.  -Jerry Fodor


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


Re: [Tutor] making math problems mmmm fun

2007-09-11 Thread David Perlman
Also keep in mind that if you want your code to work, your grammar  
and punctuation in code has to be absolutely flawless.  Writing  
English well is excellent practice for writing code well; writing  
English poorly is excellent practice for writing code poorly.

You get what you pay for.  If you put in the effort, you will reap  
the reward.  If you don't put in the effort, you will reap the reward  
of that instead, which is "teh suck"...  :)

On Sep 11, 2007, at 7:38 AM, Luke Paireepinart wrote:

> max baseman wrote:
>> lol sorry i was born with bad grammar and hand writing (although it's
>> the bit after being born that matters)
>>
> Just imagine you're talking instead of writing.  Everywhere you'd  
> put a
> pause, put a comma.  If it seems like the end of a sentence, put a
> period.  In most cases, even bad punctuation will be better than no
> punctuation.  People's inner monologues will just take on a  
> Christopher
> Walken accent as they read over your e-mails, but this is arguably  
> not a
> bad thing.
> Grammar is something you can learn, not something inborn. Now is as  
> good
> a time as any to start learning it.
> -Luke
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

--
-dave
All I ask is that the kind of unsolvable that it turns out to be has
respectable precedents.  -Jerry Fodor


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


Re: [Tutor] automate daily tasks

2007-09-11 Thread David Perlman
As far as making something run automatically at various times, if  
you're certain that you want to do it in a Mac-only way, Apple's  
recommended method for timing jobs is described here:
http://developer.apple.com/macosx/launchd.html
"Getting started with launchd"
otherwise use cron or at, as Tom said.


On Sep 11, 2007, at 11:54 AM, chinni wrote:

> I am working on MAC OS x my project is updating all ready installed  
> products.I have to automate this in python.so,can any one will give  
> some suggestions and some examples how to automate.some basic  
> things of my project is ... i think u all know that there will be a  
> plist file for each product in mac.i have to degrade the version of  
> plist automatically through my script and it has to edit the plist  
> file and degrade it to least version and as to check for updates by  
> itself.like this there are 15 products under this now each time i  
> can't go and degrade the version and save it and run updates  
> manually..so,that can any one plz..tell me how to start from first  
> step...

--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



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


Re: [Tutor] control multiple FTP sessions using multiple ipconnectionsvia different com ports

2007-02-19 Thread David Perlman
This kind of thing is usually handled at the level of the OS's  
routing table.  Routing tables have an entry called "metric" that is  
used to weight the different routes, so that when there are multiple  
possible links available, the one with the lowest metric is used  
first.  In Unix at least, you'll be able to use either the command  
"route" or "routed" to manually change the routing table; you can  
change the metrics for the two interfaces to control which one gets  
used.  unfortunately this will change the routing globally, not just  
for a specific connection.  I don't think the routing systems on  
ordinary computers were designed with the idea in mind that you might  
want to use a specific link for a specific connection.

If you're on UNIX, run netstat -nr.  If you're on Windoze, run route  
print.  You should be able to see the metric for each entry.
http://www.pku.edu.cn/academic/research/computer-center/tc/html/ 
TC0310.html
Unfortunately, the "metric" column doesn't show up under OS X, and I  
haven't been able to figure out why in 5 minutes of searching.  Also  
unfortunately, I don't know any more about this, and searching on  
Google was not revealing immediate results.  But hopefully this will  
get you started in the right direction!

So the bottom line, I guess, is that a) this is a routing question,  
not a python question; and b) it's not an easy question.  :)

On Feb 19, 2007, at 3:53 AM, ray sa wrote:

> Hi
>
> Well now I have configured an old machine in the garage to run at  
> the same time.
>
> I would really like to find out how to do this as it must be  
> possible. I have been googling like mad and can't find how. Kind of  
> frustrating when you don't know how. At the same time a challenge  
> to seek.
>
> I am kind of hoping that someone on this forum will know how. In  
> the mean time I can continue with my testing.
>
> Many thanks for your help; really appreciate it.
>
> /Ray
>
> Johan Geldenhuys <[EMAIL PROTECTED]> wrote:
> Will it be possible to disconnect one of the links during your test  
> and reconnect it and disconnect the other connection once the ftp  
> test is finished on the first connection? This way it will force  
> the test script to use the active route to the internet.
>
> Not the most elegant way, but something to look at in the mean time.
>
> Johan
>
> From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On  
> Behalf Of ray sa
> Sent: 18 February 2007 04:16 AM
> To: Alan Gauld; tutor@python.org
> Subject: Re: [Tutor] control multiple FTP sessions using multiple  
> ipconnectionsvia different com ports
>
> Hi Alan et al
>
> Many thanks for your time on this.
>
> I was referring to the client end.
>
> An EDGE terminal is a phone that has the capability of connecting  
> to the internet. We use mobile phones to make a voice call that  
> make use of a circuit switched connection. By using a GPRS  
> connection we can use the mobile device to connect to the packet  
> switched domain. You might have heard about making data connection  
> using your phone like GPRS, 3G etc. EDGE is just faster than a GPRS  
> connection and 3G is supposedly faster than GPRS and EDGE.
>
> May be I can give you more information about what I am trying to  
> do. So you can understand what I am trying to achieve. Basically, I  
> am trying to decide whether I should change my ADSL fixed solution  
> to a higher speed connection using a mobile solution. Where I live  
> the mobile operator is offering a mobile solution which is cheaper  
> than my fixed solution….and is faster than my ADSL connection,  
> please read on
>
> I have my ADSL broadband connection to my service provider that I  
> use to connect to the internet. I have just bought a GPRS/EDGE/3G  
> terminal and wanted to benchmark the speed I am getting by using my  
> mobile device as opposed to my fixed connection.
>
> My desktop machine is connected to my ADSL provider using a USB  
> modem which is assigned a particular COM port on my machine. Then I  
> have connected my mobile handset also using a USB connection  
> connected to a different COM port.
>
> Now I have two ip addresses
>
> ADSL – COM port 4 with ip addres from my ADSL service provider
> Mobile Handset – COM port 5 with another ip address from my mobile  
> provider
>
> I have written a script that connects to a ftp server within my  
> home country and downloads a file. But this script uses one of the  
> connections above. There must be away to tell the script and  
> control which connection to use. So I can get to see real time  
> which connection is faster. So I can run the script pointing to one  
> IP address and at the same time run another script using the other  
> connection.
>
> I think there must be a method that finds out which connection is  
> connected to which com port and then in my script I need to point  
> towards that connection so my script knows which channel to use  
> when downloading the file.
>
> I hope this helps

Re: [Tutor] Struct the solution for Hex translation

2007-02-19 Thread David Perlman
You're way off base... :)

On Feb 19, 2007, at 9:25 AM, Johan Geldenhuys wrote:

>  Here is what I have:
>
 data
> '\xa5\x16\x0b\x0b\x00\xd5\x01\x01\x01\x00\x00\xe3\x84(\x01\xc6\x00 
> \x00\x17\x
> 01C\xc7'
 data[0]
> '\xa5'
 len(data[0])
> 1

>
> You see that data[0] is only one byte and it doesn't see all four
> characters.
>
> If I want to do this:
>
 int(data[0], 16)
>   File "", line 1, in ?
> ''' exceptions.ValueError : invalid literal for int(): ¥ '''
>
>
> But I can do this:
>
 int('a5', 16)
> 165

>
> If I use data[0] as it is, I get errors. That why I want to know  
> how I can
> strip away the '\x'.

This is what you want to do:
 >>> import struct
 >>> struct.unpack('B',data[0])
(165,)

Once again, the \x doesn't really exist, any more than the quotation  
marks do.  They're just ways of indicating on the screen what kind of  
data is being displayed.

> Here is some other code to convert Hex to Binary:
>
> hex2bin = {
> "0" : "", "1" : "0001", "2" : "0010", "3" : "0011",
> "4" : "0100", "5" : "0101", "6" : "0110", "7" : "0111",
> "8" : "1000", "9" : "1001", "a" : "1010", "b" : "1011",
> "c" : "1100", "d" : "1101", "e" : "1110", "f" : ""
> }
>
 def hexBin(hexchars):
> ... s = ""
> for hexchar in hexchars:
> s += hex2bin[hexchar]
> return s.rstrip("\n")
> ...
 hexBin('a5')
> '10100101'
>
> This however does not work if my argument is '\xa5'.
>
 hexBin('\xa5')
>   File "", line 1, in ?
>   File "", line 5, in hexBin
> ''' exceptions.KeyError : '\xa5' '''


This function is useless in this case because you don't actually have  
a string of letters and numbers; you just have raw binary data.

--
-dave
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama



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


Re: [Tutor] Function for converting ints from base10 to base2?

2007-02-20 Thread David Perlman
I suspect the function I sent out earlier, using octal conversion and  
a lookup table, will be faster.  But it would be very interesting to  
see some simple benchmarks.

On Feb 20, 2007, at 10:47 PM, Dick Moores wrote:

> I was surprised to be unable to find a function in Python for
> converting ints from base10 to base2. Is there one?
>
> I wrote one, but have I reinvented the wheel again? (Even if I have,
> it was an interesting exercise for me.)
>
> I know some of you CS people won't like what I do with negative ints,
> but I wanted it this way. On other points than that, I'd appreciate
> criticism/suggestions.
>
> ===
> def computeBin(n):
>  """converts base10 integer n to base2 b as string"""
>  from math import log, floor
>  sign = ''
>  if n == 0:
>  b = '0'
>  else:
>  if n < 0:
>  sign = "-"
>  n = -n
>  e = int(floor(log(n,2)))
>  b = '1'
>
>  for x in range(e):
>  r = n % 2**e
>  if r >= 2**(e-1):
>  b += '1'
>  else:
>  b += '0'
>  e -= 1
>  return sign + b
>
> def printResult(n,b):
>  print "%d is %s" % (n, b)
>
> def confirmResult(n,b):
>  print "Confirming using int():"
>  print "int(%s,2) is %s" % (b, int(b,2))
>
> if __name__ == '__main__':
>  n = 1234567890
>  b = computeBin(n)
>  printResult(n,b)
>  confirmResult(n,b)
> ==
>
> Dick Moores
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

--
-dave
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama



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


Re: [Tutor] Function for converting ints from base10 to base2?

2007-02-21 Thread David Perlman
d'oh, I fell for the "reply-all" trick.  :)

Here's the code in question:

Apparently there are built in functions hex() and oct() to generate  
hexadecimal and octal digit strings of numbers, but there's no  
corresponding bin().  Kind of a bizarre oversight, if you ask me.

Searching on the internet, I found this:

def bin(integer, returnType=str):
bin =  
{'0':'000','1':'001','2':'010','3':'011','4':'100','5':'101','6':'110',' 
7':'111'}
if returnType == int:
return int(''.join([bin[i] for i in oct(integer)]))
elif returnType == long:
return long(''.join([bin[i] for i in oct(integer)]),10)
else:
return (''.join([bin[i] for i in oct(integer)])).lstrip("0")

Just define this in the program you are writing and use bin as you
would use oct or hex, making sure to specify int or long as the return
type if you don't want a str.

On Feb 21, 2007, at 1:18 AM, Dick Moores wrote:

> Well, I can't compare mine with yours (where is it?), but using the  
> template in timeit.py:
>
> template = """
> def inner(_it, _timer):
> from decToBin import computeBin
> _t0 = _timer()
> for _i in _it:
> computeBin(12345678901234567890)
> _t1 = _timer()
> return _t1 - _t0
> """
> I get these results:
>
> for computeBin(12345678901234567890)
> 1000 loops, best of 3: 448 usec per loop
>
> for computeBin(1234567890)
> 1 loops, best of 3: 59.7 usec per loop
>
> for computeBin(12345)
> 1 loops, best of 3: 35.2 usec per loop
>
> Dick Moores
>
> At 09:04 PM 2/20/2007, David Perlman wrote:
>> I suspect the function I sent out earlier, using octal conversion and
>> a lookup table, will be faster.  But it would be very interesting to
>> see some simple benchmarks.
>>
>> On Feb 20, 2007, at 10:47 PM, Dick Moores wrote:
>>
>> > I was surprised to be unable to find a function in Python for
>> > converting ints from base10 to base2. Is there one?
>> >
>> > I wrote one, but have I reinvented the wheel again? (Even if I  
>> have,
>> > it was an interesting exercise for me.)
>> >
>> > I know some of you CS people won't like what I do with negative  
>> ints,
>> > but I wanted it this way. On other points than that, I'd appreciate
>> > criticism/suggestions.
>> >
>> > ===
>> > def computeBin(n):
>> >  """converts base10 integer n to base2 b as string"""
>> >  from math import log, floor
>> >  sign = ''
>> >  if n == 0:
>> >  b = '0'
>> >  else:
>> >  if n < 0:
>> >  sign = "-"
>> >  n = -n
>> >  e = int(floor(log(n,2)))
>> >  b = '1'
>> >
>> >  for x in range(e):
>> >  r = n % 2**e
>> >  if r >= 2**(e-1):
>> >  b += '1'
>> >  else:
>> >  b += '0'
>> >  e -= 1
>> >  return sign + b
>> >
>> > def printResult(n,b):
>> >  print "%d is %s" % (n, b)
>> >
>> > def confirmResult(n,b):
>> >  print "Confirming using int():"
>> >  print "int(%s,2) is %s" % (b, int(b,2))
>> >
>> > if __name__ == '__main__':
>> >  n = 1234567890
>> >  b = computeBin(n)
>> >  printResult(n,b)
>> >  confirmResult(n,b)
>> > ==
>> >
>> > Dick Moores
>> >
>>
>> --
>> -dave
>> After all, it is not *that* inexpressible.
>> -H.H. The Dalai Lama
>
>

--
-dave
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama



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


Re: [Tutor] geeks like us and the rest of THEM

2007-02-25 Thread David Perlman
Keep in mind that things generally become extremely reliable only  
after extensive real-world testing.  TANSTAAFL

On Feb 25, 2007, at 1:14 AM, Kirk Bailey wrote:

> This has to be baby carriage reliable and simple for the business road
> warrior who has not a geekified bone in their body.

--
-dave
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama



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


Re: [Tutor] Group sequence pairwise

2007-02-25 Thread David Perlman
I found this by "using Google".  You should be able to make a simple  
modification (I can think of a couple of ways to do it) to have it  
pad the end with "None".  It is 100% iterator input and output.

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

On Feb 25, 2007, at 7:06 AM, Christopher Arndt wrote:

> Luke Paireepinart schrieb:
>> Christopher Arndt wrote:
>>> I have tried to find a solution, using itertools, but I'm not very
>>> experienced in functional stuff, so I got confused.
>> Do you mean you're not experienced in using functions or do you mean
>> you're inexperienced at functional programming?
>
> I mean functional programming.
>
>> Well, this is fairly simple to do with list comprehensions...
> x = [1,2,3,4,5,6,7]
> if len(x) % 2 != 0: x.append(None)
>>
> [(x[a],x[a+1]) for a in range(0,len(x),2)]
>> [(1, 2), (3, 4), (5, 6), (7, None)]
>
> I came a up with a similar solution:
>
> for i in xrange(0, len(s), 2):
> do_something(s[i])
> if i+1 <= len(s):
>   do_something(s[i+1])
> else:
> do_something(None)
>
> or
>
> try:
> for i in xrange(0, len(s), 2):
> do_something(s[i])
>   do_something(s[i+1])
> except IndexError:
> do_something(None)
> raise StopIteration
>
>> Dunno if that's what you're after,
>
> Not exactly. I wonder if this is possible without modifying the  
> original
> sequence (could be not a list too) and I'd also like to find a  
> solution
> that generally applies to iterables.
>
> Chris
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

--
-dave
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama



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


Re: [Tutor] Telnet and special characters

2007-02-28 Thread David Perlman
This question isn't well posed.  There is no such thing as an F1  
"character".

Data is sent over telnet connections as 8-bit bytes.  You can send  
any combination of 8-bit bytes you want by coding them in a number of  
different ways, such as chr(xx) like you wrote below, or '\xnn' or  
whatever suits your fancy.  The reason you are having problems is  
that you don't know what bytes you want to send over the connection.   
If you figure that out, then you will be able to send those bytes  
without any further trouble.

If you're having trouble figuring out what bytes you want to send  
over the connection, you need to take a step back and ask what it is  
you're actually trying to do.  What are you sending the data to?  Are  
you trying to emulate something else that would normally be sending  
the data?  Find the documentation for the sending and/or receiving  
ends, and figure out what combinations of characters, escape  
sequences, whatever, are involved in triggering the behavior that you  
want.  Then you will know what bytes you want to send.

If you are emulating something else on the client end, you could fire  
up the regular client and sniff the connection while you hit whatever  
'F1' key you're interested in, and see what actually gets sent over  
the connection when you do that.

On Feb 27, 2007, at 12:08 PM, Chris Hallman wrote:

>
> Is it possible to send a F1 "character" over a telnet connection?  
> I've searched but I can't find a solution. I've tried SendKeys and  
> other methods, but I can't get it to work.
>
> import telnetlib
>
> pswd = "***"
> host = "***"
> tn = telnetlib.Telnet(host)
> tn.read_until("password:", 7)
> tn.write(pswd + "\n")
> tn.write(chr(27)) # ESC
> tn.write (chr(78)) # Shift N
> tn.write(chr(25)) # Down arrow
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

--
-dave
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama



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


Re: [Tutor] Two sys.exit questions

2007-02-28 Thread David Perlman
If you want to play around with this stuff, you can first import sys,  
and then insert this line in the except clause:
print repr(sys.exc_info())
(or some other way of getting the details out of the returned tuple.)

That will tell you exactly what brought you to the except clause.

On Feb 28, 2007, at 12:07 PM, Jason Massey wrote:

> When you call sys.exit() you're raising a SystemExit exception.
>
> >>> help(sys.exit)
> Help on built-in function exit in module sys:
>
> exit(...)
> exit([status])
>
> Exit the interpreter by raising SystemExit(status).
> If the status is omitted or None, it defaults to zero (i.e.,  
> success).
> If the status is numeric, it will be used as the system exit  
> status.
> If it is another kind of object, it will be printed and the system
> exit status will be one (i.e., failure).
>
> So that explains why you're falling through to except clause.
> You can see the same type of behavior if you manually raise an  
> exception (ValueError for example) within a try clause
>
> In your example concerning the reading and writing to files, as far  
> as a close() statement goes you would get this error:
> >>> try:
> ... i_file = open('doesnt_exit.tmp','r')
> ... except IOError:
> ... i_file.close()
> ...
> Traceback (most recent call last):
>   File "", line 4, in ?
> NameError: name 'i_file' is not defined
> >>>
>
> Since i_file never got defined because the open wasn't successful.
>
> BTW don't use file as a variable since it will mask python's built- 
> in file object
>
> On 2/28/07, Cecilia Alm <[EMAIL PROTECTED]> wrote:I have two quick  
> questions:
>
> 1) Why does sys.exit() not work in a try clause (but it does in the  
> except clause)?
>
> >>> try:
> ...print 1
> ...sys.exit(0)
> ... except:
> ...print 2
> ...sys.exit(0)
> ...
> 1
> 2
> # python exited
>
> 2) If opening a file fails in the below 2 cases, sys.exit(message)  
> prints a message in the except clause before program termination.
> Some use file.close() in the except clause (or in a finally  
> clause). It seems superflous in the below case of read and write. (?)
>
> try:
> file = open('myinfile.txt', 'r')
> except IOError:
> sys.exit('Couldn't open myinfile.txt')
>
> try:
> file = open('myoutfile.txt', 'w')
> except IOError:
> sys.exit('Couldn't open myoutfile.txt')
>
>
>
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

--
-dave
Science arose from poetry... when times change the two can meet again
on a higher level as friends. -Göthe


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


Re: [Tutor] Yet another list comprehension question

2007-03-02 Thread David Perlman

On Mar 2, 2007, at 9:56 AM, Alan Gauld wrote:

> Why not use a Set?
>
> s = Set([somefun(i) for i in some-iterator])
>
> Might be slow for big lists though...

I'm curious why using a Set would be slower than doing it in a loop?   
In either case, the processor has to scan through all the data  
looking for duplicates.  I suppose in this case it's doing it in two  
passes, though.  On the other hand, the "not in l" check has to scan  
through the whole l each time.

I'd be really interested in seeing benchmarks comparing the  
methods...  no time to do it myself though... :)

--
-dave
Science arose from poetry... when times change the two can meet again
on a higher level as friends. -Göthe


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


Re: [Tutor] trouble with function-- trying to check differences btwn 2 strings

2007-03-06 Thread David Perlman
OK, I'm new to python too so I don't assume I know what I'm talking  
about yet, but this looks like a mess to me.  What exactly does "item  
== item in word2" evaluate to?  Does "in" or "==" have higher  
precedence?

I can't figure out how this would ever work at all.  It seems like  
it's either checking to see whether boolean TRUE is in word2, or else  
it's checking to see whether item is equal to boolean TRUE or FALSE,  
and neither of those should ever be true.  And yet it seems to be  
working out the same as "item in word2".  So what exactly is python  
doing here?

On Mar 5, 2007, at 5:13 PM, Rikard Bosnjakovic wrote:

> On 3/6/07, zannah marsh <[EMAIL PROTECTED]> wrote:
>
>> if item == item in word2: #checks characters against each  
>> other
>
> Here's the error.
>
> Loop variable "item" contains the actual character in word1. The
> syntax "item in word2" checks if this character is _anywhere_ in
> word2. What you want to do is rewriting this loop so it checks
> character per character. Since it's for homework, I don't want to ruin
> your grades by giving you a solution. Try it yourself first.
>
> To see what I mean, try running getDiff("abcd", "dcba").
>
>
> -- 
> - Rikard.
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

--
-dave
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama



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


Re: [Tutor] trouble with function-- trying to check differences btwn 2 strings

2007-03-06 Thread David Perlman
On Mar 6, 2007, at 11:03 AM, Alan Gauld wrote:
> It's doing the latter and since anything that's not 'empty' in
> Python evaluates to true we wind up checking whether
> true == (item in word)
>
> So if the item is in word we get true == true which is true.
>
> HTH,

Sorry, but this still doesn't make sense to me.

 >>> x=('i' in 'i')
 >>> x
True
 >>> y='i'
 >>> x==y
False

I understand that anything that's not 'empty' or zero evaluates to  
True *when cast as a Boolean* by the operation in question:

 >>> if y: print "It's True!"
...
It's True!

But the == operator doesn't cast its operands as Booleans; it merely  
*returns* a Boolean.

Or is the point that in the original case the == operator *is*  
casting item to Boolean because it's comparing it with another  
Boolean?  That's kind of strange, especially considering that in my  
example above, it *didn't* do that.

I still don't understand what's going on.  :)

--
-dave
Science arose from poetry... when times change the two can meet again
on a higher level as friends. -Göthe


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


Re: [Tutor] trouble with function-- trying to check differences btwn 2 strings

2007-03-06 Thread David Perlman

On Mar 6, 2007, at 4:28 PM, wesley chun wrote:

>>  >>> x=('i' in 'i')
>>  >>> x
>> True
>>  >>> y='i'
>>  >>> x==y
>> False
>
> you're right when you talk about "casting" altho that's not what
> python does.  it merely performs an object value comparison when you
> use '=='.  for example, change your code above to:
>
 True == 'i'# because this is what you're really doing with x==y
> False
>
> so the reason why you get a false is that those 2 values *are*
> different from each other, even if their boolean truthfulness may be
> the same:
>
 bool(True) == bool('i')
> True
>
> how's *that* for casting?  :-)
>
> just remember that the interpreter compares *values* and not boolean
> truthfulness, and you'll be ok.  if you really want the latter, then
> use bool().
>
> hope this helps!
> -- wesley

This helps convince me that I still don't understand why the original  
code snippet worked at all.  :)

These code examples make perfect sense.  This one doesn't, and  
appears to be an inconsistency:

 >>> word2 = 'hello'
 >>> item = 'e'
 >>> item in word2
True
 >>> item == item in word2
True
 >>> (item == item) in word2
Traceback (most recent call last):
   File "", line 1, in ?
TypeError: 'in ' requires string as left operand
 >>> item in word2
True
 >>> item == True
False
 >>> item == (item in word2)
False

Notice that forcing the precedence of "in" and "==" using parentheses  
gives either False or an error, but without parentheses, it's True.   
So what's going on?


--
-dave
Science arose from poetry... when times change the two can meet again
on a higher level as friends. -Göthe


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


Re: [Tutor] trouble with function-- trying to check differences btwn 2 strings

2007-03-06 Thread David Perlman
I think it's a little strange and possibly problematic that type(1)  
is 'int' and type(True) is 'bool' but
1 == True
specifically evaluates to True even though anything else, even if it  
evaluates to True when cast as a boolean, is not == True.

 >>> 1 == True
True
 >>> 2 == True
False
 >>> 0 == False
True
 >>> 2 == False
False

I guess I just need to remember to always look on the bright side of  
life.

On Mar 6, 2007, at 4:44 PM, John Fouhy wrote:

> 'foo == bar in baz' should group as '(foo == bar) in baz'.  But Luke's
> example contradicts this:
>
 lst = [1,2,3,4]
 555 == 555 in lst
> False
 (555 == 555) in lst
> True
 1 == 1 in lst
> True
>
> (this works because 1 == True)

--
-dave
Science arose from poetry... when times change the two can meet again
on a higher level as friends. -Göthe


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


[Tutor] Interactive plots...

2008-03-27 Thread David Perlman
I am thinking about writing a program which will involve, among other  
things, displaying a plot of a series of numbers.  The idea is that  
you could click on the points and move them to change the numbers.   
Reverse-plotting, I suppose.  It need not be complex; the numbers  
will all be zero or one, and it's only necessary to flip the bits, so  
click-and-drag is seriously overkill.  Really it would be better to  
just double-click on a point to switch it from one value to the other.

Can anyone point me in the right direction?  I have written some  
programs in python before, including TKinter, but this new project is  
beyond the point that I know where to even start looking.  :)

In case you care, the application is in functional brain imaging; the  
brain scans generate a certain number of time points (say 500) and  
then the motion of the subject is also calculated.  Standard practice  
is to generate a "censor" file composed of zeros and ones, where zero  
indicates that that time point had excessive motion and must be  
disregarded.  I want to display a graph of the motion over time, and  
allow quick and easy interactive editing of the censor time series in  
visual parallel to the motion graph.  This would save a lot of time;  
at present everyone does this in Excel, which being a horrible  
Windows program can't be integrated into the predominantly UNIX-based  
processing pipeline.  And in any case, it requires manually typing  
all the zeros, looking back and forth between the graph of motion and  
the list of numbers.

I have already written a program to algorithmically generate the  
censor time series from the motion data, but it is absolutely  
essential to be able to manually double-check and if necessary make  
minor edits.  I'd like to be able to keep that functionality in  
Python rather than sending everyone back to Excel...  if possible!

Thanks very much for any help.

--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



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