RE: something about split()???

2012-08-14 Thread Andreas Tawn
> I have a question about the split function? surpose a = "|",and when I use 
> a.split("|") , I got the list
> ['"",""] ,but I want to get the empty list,what should I do ?

Something like...

>>> [x for x in "|".split("|") if x]
[]

Cheers,

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


RE: Dealing with the __str__ method in classes with lots of attributes

2012-05-14 Thread Andreas Tawn
> p.s. Is Python seeing a lot of use at Ubisoft or is this just for personal 
> interest (or
> perhaps both)?

We do use Python a fair bit, mostly for build systems and data mining, but also 
because it's the built-in script language for Motionbuilder.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Dealing with the __str__ method in classes with lots of attributes

2012-05-11 Thread Andreas Tawn
> >> It's also helpful to not have to display every attribute, of which
> >> there may be dozens.
> >
> > Do I detect a code smell here?
> >
> I think so, Murphy's law dictates that the attribute you're interested in 
> will not be
> displayed anyway.

That's what __repr__'s for.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Dealing with the __str__ method in classes with lots of attributes

2012-05-11 Thread Andreas Tawn
> > It's also helpful to not have to display every attribute, of which there 
> > may be
> dozens.
> 
> Do I detect a code smell here?

Possibly. I'll often try to subdivide into several simpler types, but sometimes 
that makes the code more complex than it needs to be.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Dealing with the __str__ method in classes with lots of attributes

2012-05-11 Thread Andreas Tawn
> I have no idea why using __repr__ versus __str__ would make any difference in 
> the
> order of the attributes. They're going to come out in the order you specify,
> regardless of what you name your method.  If you don't like the arbitrary 
> order you
> get from the dictionary, then either sort it, or provide an explicit list.

Only that, as the docs say, __repr__ should represent the entire object that 
could be used to build a new object with the same value. For that task the 
order of the attributes is immaterial.

I want __str__ to give me something easily readable and ordered in a way that's 
conveys some meaning about the attributes. It's also helpful to not have to 
display every attribute, of which there may be dozens.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Dealing with the __str__ method in classes with lots of attributes

2012-05-11 Thread Andreas Tawn
> This issue bit me once too often a few months ago, and now I have a class 
> called
> "O" from which I often subclass instead of from "object".
> Its main purpose is a friendly __str__ method, though it also has a friendly 
> __init__.
> 
> Code:
> 
> class O(object):
>   ''' A bare object subclass to allow storing arbitrary attributes.
>   It also has a nicer default str() action, and an aggressive repr().
>   '''
> 
>   def __init__(self, **kw):
> ''' Initialise this O.
> Fill in attributes from any keyword arguments if supplied.
> This call can be omitted in subclasses if desired.
> '''
> for k in kw:
>   setattr(self, k, kw[k])
> 
>   def __str__(self):
> return ( "<%s %s>"
>  % ( self.__class__.__name__,
>  ",".join([ "%s=%s" % (attr, getattr(self, attr))
> for attr in sorted(dir(self)) if 
> attr[0].isalpha()
>   ])
>)
>)

This is a very interesting solution.

I think it might be better suited (for my purpose) to __repr__ rather than 
__str__, mostly because I still lose control of the order the attributes appear.

I really like the general idea of subclassing object though, because I often 
have classes with dozens of attributes and __init__ gets very messy.

Chris' dynamically generated format string looks to be my best bet in the 
absence of a perfect solution.

Cheers,

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


RE: Dealing with the __str__ method in classes with lots of attributes

2012-05-10 Thread Andreas Tawn
> On Thu, May 10, 2012 at 11:33 PM, Andreas Tawn 
> wrote:
> > Say I've got a class...
> >
> > class test(object):
> >    def __init__(self):
> >        self.foo = 1
> >        self.bar = 2
> >        self.baz = 3
> >
> > I can say...
> >
> > def __str__(self):
> >   return "foo: {0}\nbar: {1}\nbaz: {2}".format(self.foo, self.bar,
> > self.baz)
> 
> This might be of use:
> 
> return """foo: {foo}
> bar: {bar}
> baz: {baz}""".format(**self.__dict__)
> 
> You're repeating yourself a bit, but this allows the labels to differ from 
> the format
> tags. If you're certain that you don't need that flexibility, you could 
> generate the
> format string dynamically:
> 
> return "\n".join(x+": {"+x+"}" for x in
> ("foo","bar","baz")).format(**self.__dict__)
> 
> That scales more nicely as the number of elements desired increases (while 
> still
> being 100% explicit - the presence and order of elements is governed by the 
> tuple),
> but is a bit inflexible and complicated.
> I'd be inclined toward the triple-quoted-string one.

I considered the triple quote string one, but it's not very PEP 8 compatible in 
a real class because it includes the indentation in the formatted string.

To make it print properly, it has to look like this...

def __str__(self):
return """foo: {foo}
bar: {bar}
baz: {baz}""".format(**self.__dict__)

I didn't realise I could do implicit line continuation inside a list 
comprehension. That might be the best way.

Even more so with continuation lines inside the attribute name tuple.

def __str__(self):
return "\n".join(x+": {"+x+"}" for x in
("foo",
"bar",
"baz")).format(**self.__dict__)

Still feels a bit icky though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Dealing with the __str__ method in classes with lots of attributes

2012-05-10 Thread Andreas Tawn
Say I've got a class...

class test(object):
def __init__(self):
self.foo = 1
self.bar = 2
self.baz = 3

I can say...

def __str__(self):
   return "foo: {0}\nbar: {1}\nbaz: {2}".format(self.foo, self.bar, self.baz)

and everything's simple and clean and I can vary the formatting if I need to.

This gets ugly when the class has a lot of attributes because the string 
construction gets very long.

I can do...

return "foo: {0}\nbar: {1}\nbaz: {2}".format(self.foo,
self.bar,
self.baz)

which is an improvement, but there's still a very long line.

And there's also something like...

return "\n".join((": ".join((str(k), str(self.__dict__[k]))) for k in 
self.__dict__))

which is a nice length, but I lose control of the order of the attributes and 
the formatting is fixed. It also looks a bit too much like Lisp ;o)

Is there a better way?

Cheers,

Drea

p.s. I may want to substitute __repr__ for __str__ perhaps?
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Python sets which support multiple same elements

2011-05-20 Thread Andreas Tawn
> For example, I was writing a program to detect whether two strings are
> anagrams of each other. I had to write it like this:
> 
> def isAnagram(w1, w2):
>   w2=list(w2)
>   for c in w1:
> if c not in w2:
>   return False
> else:
>   w2.remove(c)
>   return True
> 
> But if there was a data structure in python which supported duplicate
> elements(lets call it dset), then I could just write:
> 
> def inAnagram(w1,w2):
>   return dset(w1)==dset(w2)
> 
> Example of some dset methods:
> {1,2,3,3} intersection {4,1,2,3,3,3}  == {1,2,3,3}
> {1,2,3,3} union {4,1,2,3,3,3} == {1,2,3,3,3,4}
> {4,1,2,3,3,3} difference {1,2,3,3} == {4,3}
> 
> Do you think that it would be a good idea to add this kind of data
> structure to python? Or did I overlook some other easy way to solve
> this kind of problems?

Just to do the anagram problem you could do...

def isAnagram(w1, w2):
return sorted(w1) == sorted(w2)

To do the set-like operations, I guess that unless there's some itertools 
witchcraft available, you'd have to make your own dset type that inherits from 
list. Then you can define your own intersection/union etc. methods.

Cheers,

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


RE: starting a separate thread in maya

2011-05-20 Thread Andreas Tawn
> Hi,
> I'm using python2.5 in maya 2009 x64 (in linux).

For Maya/Python stuff you'll probably have more success at 
http://www.tech-artists.org/

Cheers,

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


RE: What other languages use the same data model as Python?

2011-05-05 Thread Andreas Tawn
> Steven D'Aprano wrote:
> 
> > Some day, we'll be using quantum computers without memory addresses,
> [ ...
> ] it will still be possible to
> > represent data indirectly via *some* mechanism.
> 
> :)  Cool!  Pass-by-coincidence!  And Python 3 already has dibs on the
> 'nonlocal' keyword!
> 
>   Mel.
> 

If True and False:
waveFunction.collapse(cat)


That's going to be fun ;o)

Cheers,

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


RE: Vectors

2011-04-20 Thread Andreas Tawn
> On Apr 20, 6:43 am, Andreas Tawn  wrote:
> > > Algis Kabaila  writes:
> >
> > > > Are there any modules for vector algebra (three dimensional
> > > > vectors, vector addition, subtraction, multiplication [scalar
> > > > and vector]. Could you give me a reference to such module?
> >
> > > NumPy has array (and matrix) types with support for these basic
> > > operations you mention. See the tutorial athttp://numpy.scipy.org/
> >
> > You might also want to considerhttp://code.google.com/p/pyeuclid/
> >
> > Cheers,
> >
> > Drea
> 
> Pyeuclid docs don't mention dot or cross products.
> RJB

http://partiallydisassembled.net/euclid/vector-classes.html#SECTION00222

Bottom of the page.

Cheers,

Drea

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


RE: Vectors

2011-04-20 Thread Andreas Tawn
> Algis Kabaila  writes:
> 
> > Are there any modules for vector algebra (three dimensional
> > vectors, vector addition, subtraction, multiplication [scalar
> > and vector]. Could you give me a reference to such module?
> 
> NumPy has array (and matrix) types with support for these basic
> operations you mention. See the tutorial at http://numpy.scipy.org/

You might also want to consider http://code.google.com/p/pyeuclid/

Cheers,

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


RE: Remove all directories using wildcard

2011-03-18 Thread Andreas Tawn
> I'm new to python and I am trying to figure out how to remove all sub
> directories from a parent directory using a wildcard.  For example,
> remove all sub directory folders that contain the word "PEMA" from the
> parent directory "C:\Data".
> 
> I've trying to use os.walk with glob, but I'm not sure if this is the
> right path to take.
> 
> Thanks for any suggestions!

I think I'd do something like this (untested).

import os, shutil

startDir = r"C:\Data"

for item in os.listdir(startDir):
folder = os.path.join(startDir, item)
if os.path.isdir(folder) and "PEMA" in item:
shutil.rmtree(folder)

Cheers,

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


RE: Executing functions

2011-02-11 Thread Andreas Tawn
> Can someone help me understand why Example #1 & Example #2 will run
> the functions,
> while Example #3 DOES NOT?
> Thanks for your time!
> R.D.
> 
> def One():
> print "running fuction 1"
> def Two():
> print "running fuction 2"
> def Three():
> print "running fuction 3"
> 
> 
> # Example #1
> fList = ["Two()","Three()"]
> for func in fList:
> exec func
> 
> # Example #2
> Two()
> Three()
> 
> # Example #3
> fList = ["Two()","Three()"]
> for func in fList:
> func

In example 3, func is a string literal not a function object.

Example 1 works because the exec statement parses and then evaluates the func 
string resulting in the two function calls you see.

Try this instead...

fList = [One, Two, Three]
for func in fList:
func()

Cheers,

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


RE: frequency of values in a field

2011-02-09 Thread Andreas Tawn
> How do you add all the records in the particular field of interest
> into long_list?

>From earlier in the thread you did...

import arcgisscripting
# Create the geoprocessor object
gp = arcgisscripting.create()
records_list = []
cur = gp.SearchCursor(dbfTable)
row = cur.Next()
while row:
   value = row.particular_field
   records_list.append(value)

I'd rewrite that as...

import arcgisscripting
gp = arcgisscripting.create()
cur = gp.SearchCursor(dbfTable)
records_list = [row.particular_field for row in cur]
# I've no experience of arcgis,
# so I'm assuming that SearchCursor is an iterable of some sort

Cheers,

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


RE: Namespaces

2011-01-22 Thread Andreas Tawn
> What is namespace? And what is built-in namespace?
> --
> http://mail.python.org/mailman/listinfo/python-list

http://lmgtfy.com/?q=python+namespace

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


RE: str(int_var) formatted

2010-10-29 Thread Andreas Tawn
> Hi all,
> i've to convert integer x to string, but if x < 10, the string have to
> be
> '0x' instead of simple 'x'
> 
> for example:
> 
> x = 9
> str(x) --> '09'
> 
> x = 32
> str(x) --> '32'
> 
> x represent hour/minute/second.
> 
> I can easily add '0' with a if then block, but is there a built-in way
> to
> add the '0' automatically?

>>> x = 9
>>> str(x).zfill(2)
'09'

Cheers,

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


RE: regex to remove lines made of only whitespace

2010-08-11 Thread Andreas Tawn

> On 08/11/10 06:21, Andreas Tawn wrote:
> >> I'm looking for a regex (or other solution, as long as it's quick!)
> >> that could be used to strip out lines made up entirely of
> whitespace.
> >>
> >> eg:
> >>
> >> 'x\n \t \n\ny' ->  'x\ny'
> >
> > for line in lines:
> >  if not line.strip():
> >  continue
> >  doStuff(line)
> 
> Note that the OP's input and output were a single string.

Ah, indeed. What do they say about the first part of assume?

> Perhaps something like
>  >>> s = 'x\n \t \n\ny'
>  >>> '\n'.join(line for line in s.splitlines() if line.strip())
> 'x\ny'
> 
> which, IMHO, has much greater clarity than any regexp with the
> added bonus of fewer regexp edge-cases (blanks at the
> beginning/middle/end of the text).
> 
> -tkc

This what I meant (no really) ;o).

Cheers,

Drea


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


RE: regex to remove lines made of only whitespace

2010-08-11 Thread Andreas Tawn
> Hi All,
> 
> I'm looking for a regex (or other solution, as long as it's quick!)
> that
> could be used to strip out lines made up entirely of whitespace.
> 
> eg:
> 
> 'x\n \t \n\ny' -> 'x\ny'
> 
> Does anyone have one handy?
> 
> cheers,
> 
> Chris

for line in lines:
if not line.strip():
continue
doStuff(line)

cheers,

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


RE: Multiline regex

2010-07-21 Thread Andreas Tawn
>>> I could make it that simple, but that is also incredibly slow and on
>>> a file with several million lines, it takes somewhere in the league of
>>> half an hour to grab all the data. I need this to grab data from
>>> many many file and return the data quickly.
>>>
>>> Brandon L. Harris
>>>
>> That's surprising.
>>
>> I just made a file with 13 million lines of your data (447Mb) and
>> read it with my code. It took a little over 36 seconds. There must be
>> something different in your set up or the real data you've got.
>>
>> Cheers,
>>
>> Drea
>>
> Could it be that there isn't just that type of data in the file? there
> are many different types, that is just one that I'm trying to grab.
> 
> Brandon L. Harris

I don't see why it would make such a difference.

If your data looks like...


\t
\t
\t

Just change this line...

if line.startswith("createNode"):

to...

if not line.startswith("\t"):

and it won't care what sort of data the file contains.

Processing that data after you've collected it will still take a while, but 
that's the same whichever method you use to read it.

Cheers,

Drea

p.s. Just noticed I hadn't pre-declared the currentBlock list.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: RE: Multiline regex

2010-07-21 Thread Andreas Tawn
> I could make it that simple, but that is also incredibly slow and on a
> file with several million lines, it takes somewhere in the league of
> half an hour to grab all the data. I need this to grab data from many
> many file and return the data quickly.
> 
> Brandon L. Harris

That's surprising.

I just made a file with 13 million lines of your data (447Mb) and read it with 
my code. It took a little over 36 seconds. There must be something different in 
your set up or the real data you've got.

Cheers,

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


RE: Multiline regex

2010-07-21 Thread Andreas Tawn
> I'm trying to read in and parse an ascii type file that contains
> information that can span several lines.
> Example:
> 
> createNode animCurveTU -n "test:master_globalSmooth";
> setAttr ".tan" 9;
> setAttr -s 4 ".ktv[0:3]"  101 0 163 0 169 0 201 0;
> setAttr -s 4 ".kit[3]"  10;
> setAttr -s 4 ".kot[3]"  10;
> createNode animCurveTU -n "test:master_res";
> setAttr ".tan" 9;
> setAttr ".ktv[0]"  103 0;
> setAttr ".kot[0]"  5;
> createNode animCurveTU -n "test:master_faceRig";
> setAttr ".tan" 9;
> setAttr ".ktv[0]"  103 0;
> setAttr ".kot[0]"  5;
> 
> I'm wanting to grab the information out in chunks, so
> 
> createNode animCurveTU -n "test:master_faceRig";
> setAttr ".tan" 9;
> setAttr ".ktv[0]"  103 0;
> setAttr ".kot[0]"  5;
> 
> would be what my regex would grab.
> I'm currently only able to grab out the first line and part of the
> second line, but no more.
> regex is as follows
> 
> my_regexp = re.compile("createNode\ animCurve.*\n[\t*setAttr.*\n]*")
> 
> I've run several variations of this, but none return me all of the
> expected information.
> 
> Is there something special that needs to be done to have the regexp
> grab
> any number of the setAttr lines without specification?
> 
> Brandon L. Harris

Aren't you making life too complicated for yourself?

blocks = []
for line in yourFile:
if line.startswith("createNode"):
if currentBlock:
blocks.append(currentBlock)
currentBlock = [line]
else:
currentBlock.append(line)
blocks.append(currentBlock)

Cheers,

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


RE: gui doubt

2010-06-17 Thread Andreas Tawn
> On 06/17/2010 01:04 AM, Stephen Hansen wrote:
> > On 6/16/10 10:40 PM, madhuri vio wrote:
> >> if i want to create a button
> >> which performs the transcription of dna to rna
> >> using tkinter in a gui...
> >> can u give me the method...
> >
> > You can not possibly be serious.
> 
> Oh, it's not that bad
> 
> [dna2rna.py]##
> import Tkinter as tk
> 
> root = tk.Tk()
> root.title("dna2rna")
> 
> def translate():
>from tkMessageBox import showinfo
>showinfo("Translate",
>  "Do some translating here.\n"
>  "Maybe in another thread so the GUI doesn't stall."
>  )
># do your actual work here
> 
> tk.Button(
>root,
>text="Translate!",
>command=translate
>).pack()
> root.mainloop()
> ##
> 
> Now all one needs to do is fill in the blanks in the Translate
> call to do the actual work...an exercise left for the
> professional in the field. ;-)   I suspect the GUI may need to be
> a bit more complex than that which might lead to wanting a more
> object-oriented code-base, but I leave that too as an exercise
> for the reader.
> 
> -tkc

Seems like a simple problem... or am I missing something?

def translate():
   return "dna".replace("d", "r")

Cheers,

Drea

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


RE: Need help in python plug-in development

2010-04-28 Thread Andreas Tawn
> Hi, I am new to python. I am using python 2.6. I have gone through the
> basic python and now I am trying to develop some plugin for maya 2009
> through python. So, for that I would need helping hand.

You'll probably have more luck with pymel specific stuff at 
http://www.tech-artists.org/

Cheers,

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


RE: Sleep timer but still responsive?

2010-01-29 Thread Andreas Tawn
> On Jan 28, 4:55 pm, "Gabriel Genellina" 
> wrote:
> > Please provide more details. What do you want your program to do
> while
> > sleeping? What kind of actions do you want a response to?
> > Do you have a GUI? A curses-based interfase?
> >
> > --
> > Gabriel Genellina
> 
> My app is purely console based. I just don't want the console to lock
> up (on Windows using time.sleep(x) causes the console to become
> unresponsive until the timer is done), and I want people to be able to
> CTRL+C to stop the script if need be (which can't be done if it's
> unresponsive!).
> 
> Thanks.

How about this? Responds to ctrl+c, but still sleeps.

import time

def responsiveSleep(n):
while n > 0:
time.sleep(1)
n -= 1

Cheers,

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


RE: How to print without spaces?

2009-09-18 Thread Andreas Tawn
> Hi,
> 
> I don't want to print the space between 'a' and 'b'. Could somebody
> let me know how to do it?
> 
> Regards,
> Peng
> 
> $ python
> Python 2.5.2 (r252:60911, May 21 2008, 10:08:24)
> [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> print "a","b"
> a b

print "a" + "b"

Cheers,

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


RE: Extracting patterns after matching a regex

2009-09-08 Thread Andreas Tawn
> > > Hi,
> >
> > > I need to extract a string after a matching a regular expression. For
> > > example I have the string...
> >
> > > s = "FTPHOST: e4ftl01u.ecs.nasa.gov"
> >
> > > and once I match "FTPHOST" I would like to extract
> > > "e4ftl01u.ecs.nasa.gov". I am not sure as to the best approach to the
> > > problem, I had been trying to match the string using something like
> > > this:
> >
> > > m = re.findall(r"FTPHOST", s)
> >
> > > But I couldn't then work out how to return the "e4ftl01u.ecs.nasa.gov"
> > > part. Perhaps I need to find the string and then split it? I had some
> > > help with a similar problem, but now I don't seem to be able to
> > > transfer that to this problem!
> >
> > > Thanks in advance for the help,
> >
> > > Martin
> >
> > No need for regex.
> >
> > s = "FTPHOST: e4ftl01u.ecs.nasa.gov"
> > If "FTPHOST" in s:
> >     return s[9:]
> >
> > Cheers,
> >
> > Drea
> 
> Sorry perhaps I didn't make it clear enough, so apologies. I only
> presented the example  s = "FTPHOST: e4ftl01u.ecs.nasa.gov" as I
> thought this easily encompassed the problem. The solution presented
> works fine for this i.e. re.search(r'FTPHOST: (.*)',s).group(1). But
> when I used this on the actual file I am trying to parse I realised it
> is slightly more complicated as this also pulls out other information,
> for example it prints
> 
> e4ftl01u.ecs.nasa.gov\r\n', 'FTPDIR: /PullDir/0301872638CySfQB\r\n',
> 'Ftp Pull Download Links: \r\n', 'ftp://e4ftl01u.ecs.nasa.gov/PullDir/
> 0301872638CySfQB\r\n', 'Down load ZIP file of packaged order:\r\n',
> 
> etc. So I need to find a way to stop it before the \r
> 
> slicing the string wouldn't work in this scenario as I can envisage a
> situation where the string lenght increases and I would prefer not to
> keep having to change the string.

If, as Terry suggested, you do have a tuple of strings and the first element 
has FTPHOST, then s[0].split(":")[1].strip() will work.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Extracting patterns after matching a regex

2009-09-08 Thread Andreas Tawn
> Hi,
> 
> I need to extract a string after a matching a regular expression. For
> example I have the string...
> 
> s = "FTPHOST: e4ftl01u.ecs.nasa.gov"
> 
> and once I match "FTPHOST" I would like to extract
> "e4ftl01u.ecs.nasa.gov". I am not sure as to the best approach to the
> problem, I had been trying to match the string using something like
> this:
> 
> m = re.findall(r"FTPHOST", s)
> 
> But I couldn't then work out how to return the "e4ftl01u.ecs.nasa.gov"
> part. Perhaps I need to find the string and then split it? I had some
> help with a similar problem, but now I don't seem to be able to
> transfer that to this problem!
> 
> Thanks in advance for the help,
> 
> Martin

No need for regex.

s = "FTPHOST: e4ftl01u.ecs.nasa.gov"
If "FTPHOST" in s:
return s[9:]

Cheers,

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


RE: Extract the numeric and alphabetic part from an alphanumeric string

2009-08-03 Thread Andreas Tawn

> Hi,
> 
> I have a string as str='123ACTGAAC'.
> 
> I need to extract the numeric part from the alphabetic part which I
> did using
> >>>numer=re.findall(r'\d+',str)
> >>>numer
> 123
> 
> To get the alphabetic part, I could do
> >>>alpha=str.replace('123','')
> >>>alpha
> ACTGAAC
> But when I give
> >>>alpha=str.replace(numer,'')
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: expected a character buffer object
> 
> How do I blank out the initial numeric part so as to get just the
> alphabetic part. The string is always in the same format.
> 
> Please help.
> 
> Regards,
> Sandhya

If the format's always the same, you could use slicing instead.

>>> s = '123ACTGAAC'
>>> s[:3]
'123'
>>> s[3:]
'ACTGAAC'

BTW, you should avoid using built-ins like str for variable names. Bad
things will happen.

Cheers,

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


RE: index nested lists

2009-07-28 Thread Andreas Tawn
> hi at all,
>  If I have this list:
> 
> >>> lista
> ['ciao', 1, ['mela', 'pera', 'banana'], [1, 2, 3]]
> 
> if I want enumerate elements...I can see:
> 
> >>> for parola in lista:
>   print lista[i]
>   i = i + 1
> 
> ciao
> 1
> ['mela', 'pera', 'banana']
> [1, 2, 3]
> >>>
> 
> but, if I want to enumerate elements about nested lists ??, something
> like:
> 
> ciao
> 1
> mela
> pera
> banana
> 1
> 2
> 3
> 
> ...How can I do ??
> 
> Alex
> --
> http://mail.python.org/mailman/listinfo/python-list

You could do something like this.

def printNestedList(lst):
if isinstance(lst, list):
for element in lst:
printNestedList(element)
else:
print lst

myList = ['ciao', 1, ['mela', 'pera', 'banana'], [1, 2, 3]]
printNestedList(myList)

>>>
ciao
1
mela
pera
banana
1
2
3

Cheers, Drea
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: list of all possible values

2009-07-16 Thread Andreas Tawn
> > Certainly possible with list comprehensions.
> >
>  a = "abc"
>  [(x, y) for x in a for y in a]
> > [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b',
'c'),
> > ('c', 'a'), ('c', 'b'), ('c', 'c')]
> >
> > But I like bearophile's version better.
> >
> 
> Andreas,
> 
> Thanks, but I think you were missing my point. I should have explained
better.
> 
> The advantage that bearophile's version is generic with respect to the
> number of elements in each combination. To go from 2 element pairs
> (e.g. ('a', 'c')) to 5 element pairs (e.g. ('a', 'c', 'b', 'b', 'e'))
> requires only a change in a parameter passed to itertools.
> 
> I don't see how you would do that with list comprehensions. You're
> example works nicely with 2 element pairs, but it seems to me like
> you'd need to recode it if you wanted to change it to 5 element pairs.
> 
> Am I wrong about that? Can you think of a way to write a function
> that, using list comprehensions, takes a list of values and the size
> of each combination, and returns the len(list)**(combination size)
> possible combinations using those values?
> 
> Thanks again,
> David

David,

I think my post got caught in the nebulous email eddys and seems to have
taken 16 hours to arrive on the list. It was meant to be a reply to your
first post, not your second.

Having said that, I think I missed the point of that post too ;o)

Maybe someone smarter than me can come up with a way to dynamically nest
the fors in a list comprehension, but I certainly can't do it.

Sorry for the confusion.

Cheers,

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


RE: list of all possible values

2009-07-14 Thread Andreas Tawn
> David Gibb:
> > For example: if my values are ['a', 'b', 'c'], then all possible
lists
> > of length 2 would be: aa, ab, ac, ba, bb, bc, ca, cb, cc.
> 
> >>> from itertools import product
> >>> list(product("abc", repeat=2))
> [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b',
> 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
> 
> Bye,
> bearophile

Certainly possible with list comprehensions.

>>> a = "abc"
>>> [(x, y) for x in a for y in a]
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'),
('c', 'a'), ('c', 'b'), ('c', 'c')]

But I like bearophile's version better.

Cheers,

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


RE: Specific iterator in one line

2009-06-30 Thread Andreas Tawn
> -Original Message-
> From: python-list-bounces+andreas.tawn=ubisoft@python.org [mailto:python-
> list-bounces+andreas.tawn=ubisoft@python.org] On Behalf Of Paul Rubin
> Sent: Tuesday, June 30, 2009 11:27 AM
> To: python-list@python.org
> Subject: Re: Specific iterator in one line
> 
> "Andreas Tawn"  writes:
> > list("".join([("a","b"*2)[x] for x in [1,0,0,1]])
> > 50 characters. Do I win £5?
> 
> Er, missing right paren.  Try:
> 
> list("".join(("a","bb")[x] for x in [1,0,0,1]))
> --

Indeed. Stupid paste ;o)
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Specific iterator in one line

2009-06-30 Thread Andreas Tawn
> > > This is purely sport question. I don't really intend to use the answer
> > > in my code, but I am wondering, if such a feat could be done.
> > >
> > > I have a following problem: I have a list based upon which I would
> > > like to construct a different one. I could simply use list
> > > comprehensions, but there is an additional trick: for some elements on
> > > this list, I would like to return two objects. For example I have a
> > > list of 0s and 1s and for 0 I would like to add 1 'a' and for 1 I
> > > would like to add 2 'b', like this:
> > >
> > > [1, 0, 0, 1] -> ['b', 'b', 'a', 'a', 'b', 'b']
> > >
> > > The easy way is to return a tuple ('b', 'b') for 1s and then flatten
> > > them. But this doesn't seem very right - I'd prefer to create a nice
> > > iterable right away. Is it possible to achieve this? Curiosly, the
> > > other way round is pretty simple to achieve, because you can filter
> > > objects using if in list comprehension.
> > >
> > If you'll allow me a prior "import itertools",
> >
> > >>> [i for e in [1,0,0,1] for i in itertools.repeat('ab'[e], e+1)]
> >
> > does the job in 62 characters.
> 
> list("".join([("a","b"*2)[x] for x in [1,0,0,1]])
> 
> 50 characters. Do I win £5?

list("".join([("a","bb")[x] for x in [1,0,0,1]])

Or 49 :o)
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Specific iterator in one line

2009-06-30 Thread Andreas Tawn
> > This is purely sport question. I don't really intend to use the answer
> > in my code, but I am wondering, if such a feat could be done.
> >
> > I have a following problem: I have a list based upon which I would
> > like to construct a different one. I could simply use list
> > comprehensions, but there is an additional trick: for some elements on
> > this list, I would like to return two objects. For example I have a
> > list of 0s and 1s and for 0 I would like to add 1 'a' and for 1 I
> > would like to add 2 'b', like this:
> >
> > [1, 0, 0, 1] -> ['b', 'b', 'a', 'a', 'b', 'b']
> >
> > The easy way is to return a tuple ('b', 'b') for 1s and then flatten
> > them. But this doesn't seem very right - I'd prefer to create a nice
> > iterable right away. Is it possible to achieve this? Curiosly, the
> > other way round is pretty simple to achieve, because you can filter
> > objects using if in list comprehension.
> >
> If you'll allow me a prior "import itertools",
> 
> >>> [i for e in [1,0,0,1] for i in itertools.repeat('ab'[e], e+1)]
> 
> does the job in 62 characters.

list("".join([("a","b"*2)[x] for x in [1,0,0,1]])

50 characters. Do I win £5?
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: While Statement

2009-05-22 Thread Andreas Tawn
> Im using 2.6 python and when running this

> 

> class progess():

> 

>  def __init__(self, number, total,  char):

> 

>  percentage = float(number/total*100)

>  percentage = int(round(percentage))

>  char = char * percentage

>  print char

> 

> progess(100, 999,  "*")

> 

> the "percentage = float(number/total*100)" always equals 0.0

 

Try percentage = float(number)/total*100 # The closing bracket position
is the important one

 

The problem is that you're converting to float after the int division
damage has been done.

 

Cheers,

 

Drea

 

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


RE: Printing a hex character and prefixing it correctly

2009-05-15 Thread Andreas Tawn
> If I have an integer k, for instance;
> 
> k = 32 // BASE 10
> 
> How do I get print to print it out in HEX and PREFIXED with 0x? What
> is the PROPER WAY?
> 
> This does not work:
> 
>   print "This is hex 32: ", int(k, 16)
> 
> Xav

k = 32

print "This is hex 32: ", hex(k)

Cheers,

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


RE: Python to Perl transalators

2009-03-18 Thread Andreas Tawn
> > 2009/3/17  :

> >> Could anyone suggest whether there is any Python to Perl code convertors?

> >> I found one on the net viz. Perthon. But it wasn't really helping out.

> >

 > I am just a beginner learning both the languages. Wondered if I can have some

> comparative understanding of both.

> 

> I think automatic translation would be a very bad way of getting

> understanding of both. Translating from another language to Python

> usually leads to very un-Pythonic code - syntactically correct and

> working Python, but not 'real' Python. I assume that translating from

> Python to Perl will lead to something similarly un-Perlish.

> 

> --

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

> 

> Thanks Andre for your suggestions!

 

Maybe something like www.rosettacode.org would be helpful.

 

It has (hopefully) idiomatic implementations of common programming tasks in 
many languages (Python and Perl included).

 

Cheers,

 

Drea

 

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


RE: Inverse of dict(zip(x,y))

2009-03-04 Thread Andreas Tawn
>>>So, if x and y are two lists, it is easier to make a dictionary using
>>>d = dict(zip(x,y)), but if I have d of the form, d = {x1:y1,
>>>x2:y2, ...}, what is there any trick to get lists x = [x1, x2, ...]
>>>and y = [y1, y2, ...]
>>>
>>>Cheers,
>>>Chaitanya.
>> 
>> x = d.keys()
>> y = d.values()
>
>But be aware that you lose order and of course duplicate keys:

True, but that's a result of creating the dictionary, not extracting the
keys and values later.

>>> d = dict(zip("abca", "xyzt"))
>>> d
{'a': 't', 'c': 'z', 'b': 'y'}
--
http://mail.python.org/mailman/listinfo/python-list


RE: Inverse of dict(zip(x,y))

2009-03-04 Thread Andreas Tawn
>Can someone suggest a easy method to do the inverse of dict(zip(x,y))
>to get two lists x and y?
>
>So, if x and y are two lists, it is easier to make a dictionary using
>d = dict(zip(x,y)), but if I have d of the form, d = {x1:y1,
>x2:y2, ...}, what is there any trick to get lists x = [x1, x2, ...]
>and y = [y1, y2, ...]
>
>Cheers,
>Chaitanya.

x = d.keys()
y = d.values()

Cheers,
Drea
--
http://mail.python.org/mailman/listinfo/python-list


RE: python 3 error i know the file works in python 2.6

2009-02-05 Thread Andreas Tawn
>#open file and read last names
>filename = input('name file')
>file = open(filename, 'r')
>names_list = file.readlines()
>file.close()
>#open a file for saving passwords
>outfile_name = input('Save passwords')
>outfile = open(outfile_name, 'a')
>
>
>#create a password for each name in list
>import random, string
>name = ('')
>for name in names_list:
>name_prefix = name[0:2]
>number = random.randrange(100,999)
>name_prefix = str.upper(name_prefix)
>password = name_prefix + str(number)
>whole_line = (password)
>print (password)
>outfile_name.write(whole_line)
>outfile_name.close()
>
>print (password)
> 
>error
>Traceback (most recent call last):
>  File "C:\Documents and Settings\Gary\Desktop\python\bembry\pa2.i.py",
line 21, in 
>outfile_name.write(whole_line)
>AttributeError: 'str' object has no attribute 'write'

You're trying to output to the output filename string rather that the
output file you opened with that filename.

Cheers,

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


RE: is there a shorter way to write this

2009-01-29 Thread Andreas Tawn
> I had a task in a book to pick 5 items from a list of 26 ensuring the
items are not repeated
>
>
> import random
> list = ['a','b','c','d','e','f','g','h','i','j','k','l','m',
>'n','o','p','q','r','s','t','u','v','w','x','y','z']
> word = ' '
> a = random.choice(list)
> list.remove(a)
> b = random.choice(list)
> list.remove(b)
> c = random.choice(list)
> list.remove(c)
> d = random.choice(list)
> list.remove(d)
> e = random.choice(list)
> list.remove(e)
> word = a + b + c + d + e
> print (word)
> print(list) 
 
Hmm, sounds like homework, but I'll bite.
 
How about...
 
import random, string
indices = range(26)
random.shuffle(indices)
word = "".join([string.ascii_lowercase[i] for i in indices[:5]])
print word
 
Cheers,
 
Drea
 
 
--
http://mail.python.org/mailman/listinfo/python-list


RE: Kicking off a python script using Windows Scheduled Task

2008-10-15 Thread Andreas Tawn
> Does anyone know how to properly kick off a script using Windows
> Scheduled Task? The script calls other python modules within itself.
> HERE'S THE CATCH:
> I am used to running the script directly from the command window and
> the print() is very handy for us to debug and monitor. When running
> the task from Windows Scheduled Task, we'd like to be able to view the
> command window and keep it up after the Task has completed...
> 
> I used the commands
> 
> CMD /K
> 
> cd C:\testdirectory\script_RunTests
> 
> python AutomatedTestRun.py
> 
> but when AutomatedTestRun.py calls other python modules, we don't see
> output.

Import os and add os.system("pause") at the end of AutomatedTestRun.py
to keep cmd open.

As far as not seeing any output, I haven't had any trouble with that
before. Maybe you're doing something unusual?

Have you tried using the logging module, rather than print? Might be
more useful for what you're trying to do.

Cheers,

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


RE: Extracting hte font name from a TrueType font file

2008-09-18 Thread Andreas Tawn
> -Original Message-
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED]
g] On Behalf Of Steve Holden
> Sent: Thursday, September 18, 2008 5:59 PM
> To: python-list@python.org
> Subject: Extracting hte font name from a TrueType font file
> 
> Does anyone have a Python recipe for this?
> 
> regards
>  Steve
> -- 
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC  http://www.holdenweb.com/
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

Can't help with a recipe, but here's the formal spec if want to figure
it out yourself.

http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6.html

Hope that helps.

Cheers,

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


RE: Unable to lookup keys in dictionary

2008-08-12 Thread Andreas Tawn
>I am trying to run p4python API on top of python 2.5.2 and am
extracting a dictionary from perforce. The following code returns the
output that follows it:
>
>   from P4 import P4, P4Exception
>   p4 = P4()
>   p4.port = "erased"   #deleted
>   p4.user = "erased"   #deleted
>
>   try:
>  p4.connect()
>  info = p4.run("info")
>  print info
>  p4.disconnect()
>   except P4Exception:
>  for e in p4.errors:
>print e
>
>
>   Output:
>
>
>   [{'userName': 'mfielding', 'clientRoot': 'c:\\perforce',
'monitor': 'enabled', 
>   'serverRoot': 'H:\\p4root\\', 'serverVersion':
'P4D/NTX64/2007.3/143793 (2008/01/
>   21)', 'serverDate': '2008/08/12 11:18:56 -0400 Eastern
Daylight Time', 'clientAd
>   dress': '10.24.20.97:1918', 'serverLicense': 'Mad Doc
Software, Inc. 140 users (
>   support expired 2008/05/31) ', 'serverAddress':
'rsgnwep4s1.rockstar.t2.corp:166
>   6', 'clientHost': 'nwew-mfielding', 'security':
'enabled', 'password': 'enabled'
>   , 'clientName': 'mfielding'}]
>
>   I did this to test that I was receiving a dictionary back from
the server, which I clearly am. I then followed by adding the following
lines to the code:
>
>
>   print info
>   s = info[serverVersion]
>   print s
>   p4.disconnect()
>
>   I would expect this to print out P4D/NTX64/2007.3/143793
(2008/01/23), but instead it spits out the following error:
>
>
>   Traceback (most recent call last):
> File "test.py", line 10, in 
>   s = info[serverVersion]
>   NameError: name 'serverVersion' is not defined
>
>
>   Changing "s = info[serverVersion]" to "s =
info['serverVersion']" only gives me another error, which is:
>
>
>   Traceback (most recent call last):
> File "test.py", line 10, in 
>   s = info['serverVersion']
>   TypeError: list indices must be integers
>
>
>   If anyone has any idea what is going on here, I would appreciate
the help. I've spent a few hours over the past two days trying to figure
this little quirk out, but to no avail.

It looks like you're getting a list with the dictionary as the only
element.

Try...

s = info[0]['serverVersion']

Cheers,

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


RE: isPrime works but UnBoundLocalError when mapping on list

2008-07-16 Thread Andreas Tawn
 
> Andreas Tawn wrote:
> > Terry Reedy wrote:
> >> Wrong.
> > Thank you.
> > 
> >> For loop variables continue after the loop exits.  This is 
> >> intentional.
> > I never knew that and I can't find reference to it in the docs. 
> 
> Interesting starting point. It never occurred to me
> that they might not. (So I didn't look for anything
> in the docs when they did :) ).
> 
> TJG

I don't have experience of too many other languages, but in C++ (and I
guess C)...

for (int i=0; i<10; ++i)
{
doStuff(i);
}

doStuff(i); // Error

int i;

for (i=0; i<10;++i)
{
doStuff(i);
}

doStuff(i); // No error

That's the behaviour I was expecting.

Is the Python behaviour just a happy side effect of the target list
assignment or specific design decision?

Cheers,

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


RE: isPrime works but UnBoundLocalError when mapping on list

2008-07-16 Thread Andreas Tawn
Terry Reedy wrote:
>Wrong.
Thank you.

>For loop variables continue after the loop exits.  This is 
>intentional.
I never knew that and I can't find reference to it in the docs. Can you
help me with the reasons for it?

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


RE: isPrime works but UnBoundLocalError when mapping on list

2008-07-15 Thread Andreas Tawn
>defn noob wrote:
>> isPrime works when just calling a nbr but not when iterating on a
>> list, why? adding x=1 makes it work though but why do I have to add
>> it?
>> Is there a cleaner way to do it?
>> 
>> 
>> def isPrime(nbr):
>> for x in range(2, nbr + 1):
>> if nbr % x == 0:
>> break
>> if x == nbr:
>> return True
>> else:
>> return False
>> 
> [isPrime(y) for y in range(11)]
>> 
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> [isPrime(y) for y in range(11)]
>>   File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
>> if x == nbr:
>> UnboundLocalError: local variable 'x' referenced before assignment
>> 
>> 
> map(isPrime, range(100))
>> 
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> map(isPrime, range(100))
>>   File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime
>> if x == nbr:
>> UnboundLocalError: local variable 'x' referenced before assignment
> isPrime(10)
>> False
> isPrime(11)
>> True
>> 
>> 
>> 
>> adding x=1 makes it work though:
>> 
>> def isPrime(nbr):
>> x=1
>> for x in range(2, nbr + 1):
>> if nbr % x == 0:
>> break
>> if x == nbr:
>> return True
>> else:
>> return False
>> 
>> 
> [isPrime(y) for y in range(11)]
>> [False, True, True, True, False, True, False, True, False, False,
>> False]
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>> 
>
>
>Yep - "local variable 'x' referenced before assignment" is correct.
>You state: for x in range... but x doesn't exist until initialized.
>   To save a loop, initialize x=2 (the minimum value) and loop executes
>   on pass one.
>In a straight 'C' program
>   (  for (x=1, x=(nbr+1), x++)  etc...  )
>   the x is initialized and forceably incremented.
>   seems Python does not auto initialize but does auto increment.

I think a better explanation is that in your original function, x only
existed while the for loop was running. As soon as execution hit the
break statement, x ceased to exist. When you attempted to reference it
in the next line, Python has no variable called x so it complains that x
hasn't been initialised.

A more idiomatic way to write it...

def isPrime(nbr):
if nbr <= 1:
return False
for x in xrange(2, nbr+1):
if not nbr % x:
return x == nbr

Cheers,

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


RE: boolian logic

2008-06-13 Thread Andreas Tawn
if a != b and a != c and a != d:
doStuff()
else:
doOtherStuff()

Cheers,

Drea


>HI all, I'm a bit stuck with how to work out boolian logic.
>
>I'd like to say if A is not equal to B, C or D:
>   do something.
>
>I've tried
>
>if not var == A or B or C:
>and various permutations but can't seem to get my head around it.  I'm
>pretty sure I need to know what is calulated first i.e the not or the
>'OR/AND's
>
>thanks, Marc.

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


RE: exists=false, but no complaint when i open it!?

2008-05-15 Thread Andreas Tawn
>print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet
>\training_set') returns False...
>
>i have thourogly checked the filename to be correct and if we assume
>it is what could this mean then?
>i had a problem one other time when i had renamed a file but windows
>didnt rename it compeltely apparently.

It's escape characters again.

You're asking for
'C:\Users\saftarn\Desktop\NetFlixDataSet\training_set', but Python
interprets that as 'C:\Users\saftarn\Desktop\NetFlixDataSet
raining_set', which probably doesn't exist.

The first example works by accident because backslash plus the first
letter of each folder in your path happens to not match any of Python's
string formatting characters.

Use forward slashes or double up the backslashes to stop this happening.

Cheers,

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


RE: file open/read/name etc, not working

2008-05-15 Thread Andreas Tawn
>import os
>
>print os.path.exists('C:/Python25/myPrograms/netflix/test.txt')
>d=open('C:/Python25/myPrograms/netflix/flim.txt', 'r')
>d.readline()
>
>returns true in the shell but prints no text even though the document
>contains text.
>
>d.name returns nothing, d.name() raises an error.
>--
>http://mail.python.org/mailman/listinfo/python-list

Try...

import os

print os.path.exists('C:/Python25/myPrograms/netflix/test.txt')
d=open('C:/Python25/myPrograms/netflix/flim.txt', 'r')
for line in d:
print line


And I'm guessing that's a typo in flim.txt?

Cheers,

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


RE: First Program Bug (Newbie)

2008-03-19 Thread Andreas Tawn
[snip]
>> What is the square root function in python?
>
> There's one in the math module. Use the one in gmpy if you have it.

Or raise to the power 1/power

>>> 9**(1.0/2)
3.0

Also works for cube root, quad root etc.

>>> 27**(1.0/3)
3.0

>>> 81**(1.0/4)
3.0

>>> 243**(1.0/5)
3.0

Cheers,

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


RE: Web site for comparing languages syntax

2008-02-26 Thread Andreas Tawn
>Sebastian Bassi wrote:
>> I know there is one site with wikimedia software installed, that is
>> made for comparing the syntax of several computer languages (Python
>> included). But don't remember the URL. Anyone knows this site?
>
>http://99-bottles-of-beer.net/
>
>is one such site, though I don't know about wikimedia.
>
>   Mel.

Maybe http://www.rosettacode.org ? That's a wiki.

Cheers,

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


RE: Encryption Recommendation

2008-01-28 Thread Andreas Tawn
>> I'm still using Python 2.4.  In my code, I want to encrypt a password
>> and at another point decrypt it.  What is the standard way of doing
>> encryption in python?  Is it the Pycrypto module?
>
>Usually, one doesn't store clear-text passwords. Instead, use a
>hash-algorithm like md5 or crypt (the former is in the standard lib,
don't
>know of the other out of my head) and hash the password, and store that
>hash.
>
>If a user enters the password, use the same algorithm, and compare the
>resulting hashes with the stored one.
>

Have a look at the hashlib module. Should have everything you need.

There's a write up in a recent episode of Doug Hellmann's most excellent
"Python Module of the Week".

http://blog.doughellmann.com/2008/01/pymotw-hashlib.html

Cheers,

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


RE: Hexadecimal list conversion

2007-12-20 Thread Andreas Tawn
> Hi All.
> 
> I have a list which is a line from a file:
> ['\x003\x008\x001\x004\x007\x005\x00.\x005\x000\x002\x005\x009
> \x009\x00',
> '\x002\x001\x003\x006\x002\x002\x00.\x001\x007\x004\x002\x008\
> x002\x00']
> 
> This should be in the format:
> ['381475.502599', '213622.174282']
> 
> I've tried a few options using replace (replacing "\x00" with "") and
> trying to convert from hexademical to decimal.
> 
> But nothing has worked.  Can anybody give any tips to help?
> 
> Thanks.

Somthing like:

line =
['\x003\x008\x001\x004\x007\x005\x00.\x005\x000\x002\x005\x009\x009\x00'
,
'\x002\x001\x003\x006\x002\x002\x00.\x001\x007\x004\x002\x008\x002\x00']

result = [''.join(x.split('\x00')) for x in line]

Cheers,

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


RE: Timeout test hangs IDLE

2007-12-06 Thread Andreas Tawn
> I once made a small app that used threads on IDLE.
> 
> There was a strange error when using 'print' & threads. When 
> what I printed filled the entire screen, instead of moving 
> all the text up, IDLE just hanged. Try running your code from 
> the shell instead, to see if the problem is in IDLE. 
> 
> HTH,
> Sergio

It looks like there's two issues here, an IDLE problem and a "me"
problem ;o)

I changed the countTest function to time.sleep(10) rather than a big
loop. When I run the script from the command line, the timeout triggers
properly after 5 seconds but the countTest function (running in a
seperate thread now) continues for the whole 10 seconds. This is the
"me" problem. I though that the timeout function would kill the
countTest thread, but it seems like it doesn't do that. Rather, the
timout just returns after 5 seconds with the message that the countTest
thread is still alive. I guess I need to set event flags so the
countTest function can end itself rather than trying to kill it from the
main thread?

When I run it from IDLE, everything runs correctly, but after the
countTest thread ends after 10 seconds, IDLE hangs as before. IDLE bug,
maybe?

Thanks for the help everyone.

The code looks like this now.

def countTest():# Succeeds from the command line, hangs in IDLE
import time
time.sleep(10)
return True

def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
import threading
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = None

def run(self):
try:
self.result = func(*args, **kwargs)
except:
self.result = default

it = InterruptableThread()
it.start()
it.join(timeout_duration)
if it.isAlive():
return default
else:
return it.result

def runTest():
timeout(countTest, timeout_duration=5)
print "finished"

if __name__ == "__main__":
runTest()
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Timeout test hangs IDLE

2007-12-05 Thread Andreas Tawn
 
> > On Dec 5, 6:00 am, "Andreas Tawn" <[EMAIL PROTECTED]> wrote:
> > > I'm trying to integrate the timeout function from 
> > herehttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/47
> > 3878into a
> > > long running automation script and the following code 
> > causes IDLE after
> > > 20 or 30 iterations in countTest.
> > >
> > > This is in 2.5, XP and there's no traceback.
> > >
> > > Could someone point me at the user error?
> > >
> > > Thanks in advance.
> > >
> > > def countTest():
> > > for i in xrange(1000):
> > > print i
> > > return True
> > >
> > > def timeout(func, args=(), kwargs={}, timeout_duration=1, 
> > default=None):
> > > import threading
> > > class InterruptableThread(threading.Thread):
> > > def __init__(self):
> > > threading.Thread.__init__(self)
> > > self.result = None
> > >
> > > def run(self):
> > > try:
> > > self.result = func(*args, **kwargs)
> > > except:
> > > self.result = default
> > >
> > > it = InterruptableThread()
> > > it.start()
> > > it.join(timeout_duration)
> > > if it.isAlive():
> > > return default
> > > else:
> > > return it.result
> > >
> > > def runTest():
> > > timeout(countTest, timeout_duration=5)
> > >
> > > if __name__ == "__main__":
> > > runTest()
> > 
> > I'm confused. What does it cause IDLE to do? I tried running the
> > script and it ran fine. I killed it 17346 since I have no 
> intention of
> > letting it tie up my work for your extraordinary large iteration
> > number.
> > 
> > I'm using Python 2.4 on Windows XP.
> > 
> > Mike
> 
> Sorry, I need a better proof-reader.
> 
> When I run that code, the output gets to ~26 and then IDLE (or the
> shell, I'm not sure which) hangs and there's  zero CPU activity in the
> pythonw.exe process.

Also, I should say that the the idea is that the huge iteration should
timeout after 5 seconds. I only gave it a 1000 range because I
didn't know how fast it would get through the loop. Perhaps you stopped
it before the timeout triggered?

Cheers,

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


RE: Timeout test hangs IDLE

2007-12-05 Thread Andreas Tawn
> On Dec 5, 6:00 am, "Andreas Tawn" <[EMAIL PROTECTED]> wrote:
> > I'm trying to integrate the timeout function from 
> herehttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/47
> 3878into a
> > long running automation script and the following code 
> causes IDLE after
> > 20 or 30 iterations in countTest.
> >
> > This is in 2.5, XP and there's no traceback.
> >
> > Could someone point me at the user error?
> >
> > Thanks in advance.
> >
> > def countTest():
> > for i in xrange(1000):
> > print i
> > return True
> >
> > def timeout(func, args=(), kwargs={}, timeout_duration=1, 
> default=None):
> > import threading
> > class InterruptableThread(threading.Thread):
> > def __init__(self):
> > threading.Thread.__init__(self)
> > self.result = None
> >
> > def run(self):
> > try:
> > self.result = func(*args, **kwargs)
> > except:
> > self.result = default
> >
> > it = InterruptableThread()
> > it.start()
> > it.join(timeout_duration)
> > if it.isAlive():
> > return default
> > else:
> > return it.result
> >
> > def runTest():
> > timeout(countTest, timeout_duration=5)
> >
> > if __name__ == "__main__":
> > runTest()
> 
> I'm confused. What does it cause IDLE to do? I tried running the
> script and it ran fine. I killed it 17346 since I have no intention of
> letting it tie up my work for your extraordinary large iteration
> number.
> 
> I'm using Python 2.4 on Windows XP.
> 
> Mike

Sorry, I need a better proof-reader.

When I run that code, the output gets to ~26 and then IDLE (or the
shell, I'm not sure which) hangs and there's  zero CPU activity in the
pythonw.exe process.
-- 
http://mail.python.org/mailman/listinfo/python-list


Timeout test hangs IDLE

2007-12-05 Thread Andreas Tawn
I'm trying to integrate the timeout function from here
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473878 into a
long running automation script and the following code causes IDLE after
20 or 30 iterations in countTest.

This is in 2.5, XP and there's no traceback.

Could someone point me at the user error?

Thanks in advance.


def countTest():
for i in xrange(1000):
print i
return True

def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
import threading
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = None

def run(self):
try:
self.result = func(*args, **kwargs)
except:
self.result = default

it = InterruptableThread()
it.start()
it.join(timeout_duration)
if it.isAlive():
return default
else:
return it.result

def runTest():
timeout(countTest, timeout_duration=5)

if __name__ == "__main__":
runTest()
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Last iteration?

2007-10-12 Thread Andreas Tawn
> Hello,
> can I determine somehow if the iteration on a list of values 
> is the last
> iteration?
> 
> Example:
> 
> for i in [1, 2, 3]:
>if last_iteration:
>   print i*i
>else:
>   print i
> 
> that would print
> 
> 1
> 2
> 9

Something like:

myList = [1, 2, 3]
for i, j in enumerate(myList):
if i == len(myList)-1:
    print j*j
else:
print j

Cheers,

Andreas Tawn
Lead Technical Artist
Ubisoft Reflections
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Really basic problem

2007-10-08 Thread Andreas Tawn
> > I guess this means that Python has some concept of "close 
> enough", but
> > I'll have to defer to someone more knowledgeable to explain that.
> 
> No, not really, except in the sense that any floating point 
> calculation 
> will be necessarily imprecise in that sense.
[snip]
> So typing 0.3 is the same as typing 0.2 or 
> 0.30001 as far as floating point binary values 
> are concerned.
> 
> (Although note that these results are platform dependent. 
> Your mileage 
> may vary.)
> 
> -- 
> Steven
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

After some caffeine and a head-smack, I realise that you're absolutely
right and I just made the same mistake as the OP (doh).

It does demonstrate just how sneaky floating point representations are
though.

Cheers,

Andreas Tawn
Lead Technical Artist
Ubisoft Reflections
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Really basic problem

2007-10-08 Thread Andreas Tawn
> i know this example is stupid and useless, but that's not the answer
> to my question.
> here it goes:
> 
> status = 0.0
> for i in range(10):
>status = status + 0.1
> 
>if status == 0.1:
>print status
>elif status == 0.2:
>print status
>elif status == 0.3:
>print status
>elif status == 0.4:
>print status
>elif status == 0.5:
>print status
>elif status == 0.6:
>print status
>elif status == 0.7:
>print status
>elif status == 0.8:
>print status
>elif status == 0.9:
>print status
>elif status == 1.0:
>print status
> 
> the expected output:
> 0.1
> 0.2
> 0.3
> 0.4
> 0.5
> 0.6
> 0.7
> 0.8
> 0.9
> 1.0
> 
> but it gives me instead:
> 0.1
> 0.2
> 0.4
> 0.5
> 0.6
> 0.7
> 
> why?
> 
> thanks,
> 
> m.

You've just discovered the joys of floating point number comparisons.

Consider this snippet:

status = 0.0
print (repr(status))

for i in range(10):
status += 0.1
print (repr(status))

Output:

0.0
0.10001
0.20001
0.30004
0.40002
0.5
0.59998
0.69996
0.79993
0.89991
0.99989

The issue is that 0.1 etc don't have an exact representation as floating
point.

Interestingly:

>>> 0.10001 == 0.1
True
>>> 0.30004 == 0.3
False

I guess this means that Python has some concept of "close enough", but
I'll have to defer to someone more knowledgeable to explain that.

Cheers,

Andreas Tawn
Lead Technical Artist
Ubisoft Reflections
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generating range of numbers

2007-10-03 Thread Andreas Tawn
>i just want to generate numbers in the form like:
>
>1,2,4,8,16,32.to a maximum of 1024
>using a range function

>>> a = [2**x for x in range(11)]
>>> a
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]

Cheers,

Andreas Tawn
Lead Technical Artist
Ubisoft Reflections

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


Re: interesting puzzle......try this you will be rewarded...

2007-09-07 Thread Andreas Tawn
>Basilisk96 wrote:
>> I remember seeing a more elaborate puzzle that involved coding,
>> cryptography knowledge, etc. to get through it. But what was the
link,
>> I forget now...
>
>There's this one http://www.inwardhellix.net/
>
>I haven't played it yet so I can't vouch for its quality.  (am playing 
>it now)

Maybe http://www.pythonchallenge.com/ ?

Cheers,

Drea

Andreas Tawn
Lead Technical Artist
Ubisoft Reflections
-- 
http://mail.python.org/mailman/listinfo/python-list