Re: zipfile extracting png files corrupt

2009-10-17 Thread marek . rocki
Have you tried opening the zip file in binary mode?

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


Re: How do I escape slashes the string formatting operator? (or: why is it behaving this way?)

2009-05-06 Thread marek . rocki
Dustan napisał(a):
> Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> 'HELP!%(xyz)/' % {'xyz':' PLEASE! '}
> Traceback (most recent call last):
> File "", line 1, in 
> ValueError: unsupported format character '/' (0x2f) at index 11
> >>>
>
> It doesn't like the forward slash after the closed parentheses. I
> don't know what it is expecting, but I need that slash there
> (obviously this is a simplified example).
>
> All help appreciated.

Strign formatting docs (http://docs.python.org/library/
stdtypes.html#string-formatting) say that specifying a conversion type
is mandatory. So you actually should write something like:
'HELP!%(xyz)s/' % {'xyz':' PLEASE! '}
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lisp mentality vs. Python mentality

2009-04-25 Thread marek . rocki
Ciprian Dorin, Craciun napisał(a):
> Python way:
> def compare (a, b, comp = eq) :
>  if len (a) != len (b) :
>   return False
>  for i in xrange (len (a)) :
>   if not comp (a[i], b[i]) :
>return False
>  return True
This is shorter, but I'm not sure if more pythonic:
def compare(a, b, compfunc=eq):
 return all(compfunc(aelem, belem) for aelem, belem in zip_longest
(a, b, fillvalue=object()))

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


Re: Enumerating k-segmentations of a sequence

2008-11-25 Thread marek . rocki
bullockbefriending bard napisał(a):
> I'm not sure if my terminology is precise enough, but what I want to
> do is:
>
> Given an ordered sequence of n items, enumerate all its possible k-
> segmentations.
>
> This is *not* the same as enumerating the k set partitions of the n
> items because I am only interested in those set partitions which
> preserve the order of the items. i.e. if the input sequence is (1 2 3
> 4 5), then ((1 4) (2 3) (5)) is unacceptable, whereas ((1 2) (3) (4
> 5)) is acceptable. Hence use of term 'segmentations'.
>
> e.g., for input sequence (1 2 3 4 5) and k = 3, I need a function
> which enumerates the following 3-segmentations:
>
> ((1 2 3) (4) (5))
> ((1 2) (3 4) (5))
> ((1 2) (3) (4 5))
> ((1) (2 3 4) (5))
> ((1) (2 3) (4 5))
> ((1) (2) (3 4 5))
>
> The reason I want to do this is to use it in some simple one-
> dimensional clustering, i.e. each set item (won't be just integers as
> above) will have a value of interest, and i'll select the particular
> set partition which minimises Sigma SSD (sum of squared differences
> from mean) of these values.
>
> It seems overkill to generate the full list of set partitions
> [including e.g. ((1 4) (2) (3 5))] because I intend to begin by
> sorting the input sequence such that element 1 < element 2 < ... <
> element n.
>
> Structural Recursion not being my strong point, any ideas on how to go
> about this would be much appreciated!

I'm not sure if I correctly understood the semantics of what you need.
Anyway it looks like a nice exercise in nested generators:

def segmentations(sequence, k):
assert 1 <= k <= len(sequence)
if k == 1:
yield [sequence]
else:
for headlen in xrange(1, len(sequence) - k + 2):
head, tail = sequence[:headlen], sequence[headlen:]
for tail_seg in segmentations(tail, k - 1):
yield [head] + tail_seg

for segmentation in segmentations((1, 2, 3, 4, 5), 3):
print segmentation

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


Re: Calculating timespan

2008-09-28 Thread marek . rocki
Erhard napisał(a):
> I've been looking at the date/time classes and I'm at a loss as to how
> to do this (probably too used to other platforms).
>
> I have two date/time values. One represents 'now' and the other the last
> modified time of a file on disk (from stat). I need to calculate the
> difference in time (i.e., a 'timespan') between the two so I can tell if
> the file has been modified in the past X minutes and do something to it.
>
> Thanks =)

You can subtract one datetime object from another:

from datetime import datetime, timedelta
span = datetime.now() -
datetime(year=2008,month=8,day=27,hour=12,minute=34,second=56)
if span < timedelta(minutes=37):
# do something
--
http://mail.python.org/mailman/listinfo/python-list


Re: dict generator question

2008-09-18 Thread marek . rocki
Simon Mullis napisał(a):
> Something like:
>
> dict_of_counts = dict([(v[0:3], "count") for v in l])
>
> I can't seem to figure out how to get "count", as I cannot do x += 1
> or x++ as x may or may not yet exist, and I haven't found a way to
> create default values.

It seems to me that the "count" you're looking for is the number of
elements from l whose first 3 characters are the same as the v[0:3]
thing. So you may try:
>>> dict_of_counts = dict((v[0:3], sum(1 for x in l if x[:3] == v[:3])) for v 
>>> in l)

But this isn't particularly efficient. The 'canonical way' to
construct such histograms/frequency counts in python is probably by
using defaultdict:
>>> dict_of_counts = collections.defaultdict(int)
>>> for x in l:
>>> dict_of_counts[x[:3]] += 1

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


Re: ctypes initializer

2008-08-23 Thread marek . rocki
castironpi napisał(a):
> Is there a way to initialize a ctypes Structure to point to an offset
> into a buffer? I don't know if the way I'm doing it is supported.

There is a high probability you're abusing ctypes too much, but it's
possible. The following seems to work:

from ctypes import *

class S(Structure):
_fields_ = [('x', c_uint), ('y', c_int)]
rawdata = create_string_buffer('\xEE\xFF\x78\x56\x34\x12\xFF\xFF\xFF
\xFF\xAA')

# Try to make a structure s of type S which takes its data from
rawdata
# buffer, starting at index 2
s = cast(c_void_p(addressof(rawdata)+2), POINTER(S)).contents

print hex(s.x), s.y # Should be 12345678h and -1
--
http://mail.python.org/mailman/listinfo/python-list


Re: newb loop problem

2008-08-13 Thread marek . rocki
Dave napisał(a):
> Hey there, having a bit of problem iterating through lists before i go
> on any further, here is
> a snip of the script.
> --
> d = "a1 b1 c1 d1 e1 a2 b2 c2 d2 e2 a3 b3 c3 d3 e3 a4 b4 c4 d4 e4 a5 b5
> c5 d5 e5"
> inLst = d.split()
> hitLst = []
>
> hitNum = 0
> stopCnt = 6 + hitNum
>
> for i in range(hitNum,len(inLst), 1):
>   if i == stopCnt: break
>   hitLst.append(inLst[i])
>
> print hitLst
> --
> $ python helper.py
> ['a1', 'b1', 'c1', 'd1', 'e1', 'a2']
>
>
> This works fine for my purposes, what I need is an outer loop that
> goes through the original list again and appends my next request.
>
> ie.
>
> hitNum = 5
>
> which will return:
>
> ['a2', 'b2', 'c2', 'd2', 'e2', 'a3']
>
> and append it to the previous one.
>
> ie:
>
> ['a1', 'b1', 'c1', 'd1', 'e1', 'a2']
> ['a2', 'b2', 'c2', 'd2', 'e2', 'a3']
>
>
> not really sure how to do this right now though, been trying several
> methods with no good results.
>
> btw, just creating lagged values (sort of shift registers) on the
> incoming signal
>
> Many thanks,
>
> Dave

It seems you're going through a lot of trouble just to construct the
list by hand. Why don't you try slicing?

> d = "a1 b1 c1 d1 e1 a2 b2 c2 d2 e2 a3 b3 c3 d3 e3 a4 b4 c4 d4 e4 a5 b5 c5 d5 
> e5"
> in_lst = d.split()
> hit_lst = in_lst[0:6]
> hit_lst_2 = in_lst[5:11]

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


Re: Unexpected default arguments behaviour (Maybe bug?)

2008-07-13 Thread marek . rocki
[EMAIL PROTECTED] napisał(a):
> Hi, I have just encountered a Python behaviour I wouldn't expect. Take
> the following code:
>
> 
> class Parent:
> a = 1
>
> def m (self, param = a):
> print "param = %d" % param
>
> class Child (Parent):
> a = 2
>
>
> p = Parent ()
> p.m ()
>
> c = Child ()
> c.m ()
> 
>
> I would expect to receive the following output:
> param = 1
> param = 2
>
> But actually I get:
> param = 1
> param = 1
>
> Is this the correct behaviour, and then why, or is it a bug? For
> reference, I am using Python 2.5.1 on UNIX.
>
> Thanks in advance!

I expect it's because default values for parameters are evaluated and
bound at definition time. So once "def m (self, param = a):" line
executes, the default value for parameter is forever bound to be 1.
What you can do is for example:

> def m (self, param = None):
> if param is None: param = self.a
> print "param = %d" % param

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


Re: Nested generator caveat

2008-07-06 Thread marek . rocki
Excellent explanation by Mark Wooding. I would only like to add that
the standard pythonic idiom in such cases seems to be the (ab)use of a
default argument to the function, because these get evaluated at the
definition time:
def gen0():
for i in range(3):
def gen1(i = i):
yield i
yield i, gen1()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Javascript - Python RSA encryption interoperability

2008-07-04 Thread marek . rocki
Evren Esat Ozkan napisał(a):
> Hello,
>
> I'm trying to encrypt a string with RSA. But it needs to be compitable
> with Dave's JavaScript RSA implementation*. I'm already read and tried
> lots of different things about RSA and RSA in Python. But could not
> produce the same result with the javascript library.
>
> My experiments could be seen at: http://dpaste.com/hold/60741/
>
> * JavaScript RSA Library: http://www.ohdave.com/rsa/
>
> Python libraries which I tried;
> * PyCrtypo: http://www.amk.ca/python/code/crypto.html
> * rsa library from http://www.stuvel.eu/rsa
>
> How could I create the same results with the JS library in Python.
>
>
> Any help would be appreciated
>
> Evren,

It seems that this Javascript is doing weird things to its input,
namely processing it in reverse. Try encrypting ciphertext[::-1]
instead of just ciphertext.

public_modulus_hex = '9F2E..snip..4BC7'
public_exponent_hex = '10001'
public_modulus = int(public_modulus_hex, 16)
public_exponent = int(public_exponent_hex, 16)

def encrypt(plaintext_text):
# Beware, plaintext must be short enough to fit in a single block!
plaintext = int(plaintext_text.encode('hex'), 16)
ciphertext = pow(plaintext, public_exponent, public_modulus)
return '%X' % ciphertext # return hex representation

print encrypt('12345')
print encrypt('12345'[::-1]) # Will return the value compatible with
JS output

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


Re: Wrapping a method twice

2008-06-25 Thread marek . rocki
Nicolas Girard napisał(a):
> prepend(C.f,pre)
This wraps f, returns wrapped and binds it to C.f (but the
method.__name__ is still wrapped).
> append(C.f,post)
This wraps wrapped (the one previously returned), returns wrapped (a
new one) and binds it to C.wrapped (since that is what its
method.__name__ says).
> C().f()
If you try C().wrapped() it works as expected.

So the problem is in retaining the function name. Try:

def append(method,bottom):
def wrapped(*args, **kwargs):
res = method(*args, **kwargs)
return bottom(res,*args, **kwargs)
wrapped.__name__ = method.__name__
setattr(method.im_class,method.__name__,wrapped)

def prepend(method,top):
def wrapped(*args, **kwargs):
top(*args, **kwargs)
return method(*args, **kwargs)
wrapped.__name__ = method.__name__
setattr(method.im_class,method.__name__,wrapped)
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ctypes] convert pointer to string?

2008-05-21 Thread marek . rocki
Neal Becker napisał(a):
> In an earlier post, I was interested in passing a pointer to a structure to
> fcntl.ioctl.
>
> This works:
>
> c = create_string_buffer (...)
> args = struct.pack("iP", len(c), cast (pointer (c), c_void_p).value)
> err = fcntl.ioctl(eos_fd, request, args)
>
> Now to do the same with ctypes, I have one problem.
>
> class eos_dl_args_t (Structure):
> _fields_ = [("length", c_ulong),
> ("data", c_void_p)]
> ...
> args = eos_dl_args_t()
> args_p = cast(pointer(args), c_void_ptr).value
> fcntl.ioctl(fd, request, args_p)  <<< May fail here
>
> That last may fail, because .value creates a long int, and ioctl needs a
> string.
>
> How can I convert my ctypes structure to a string?  It _cannot_ be a c-style
> 0-terminate string, because the structure may contain '0' values.

Hello. I'm not completely sure what your problem is ("may fail" is not
a good description. Does it fail or does it not?). If you want a
pointer to a structure as the third argument to ioctl, this would be
imho the easiest way to do it with ctypes:

> class eos_dl_args_t(Structure):
> _fields_ = [("length", c_ulong), ("data", c_void_p)]
> args = eos_dl_args_t()
> fcntl.ioctl(fd, request, byref(args))

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


Re: Given a string - execute a function by the same name

2008-04-28 Thread marek . rocki
One solution may be to use globals():

>>> globals()['foo']()

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


Re: Form sha1.hexdigest to sha1.digest

2008-04-06 Thread marek . rocki
Martin v. Löwis napisał(a):
> > Or hexdigest_string.decode('hex')
>
> I would advise against this, as it's incompatible with Python 3.

I didn't know that, you actually made me look it up in the Python 3
FAQ. And yes, the difference is that decode will return bytes type
instead of a string. This may or may not be a problem (bytes type is
supposed to be immutable, so it can be used in many places where a
string is used now, ex. as a dict key).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Form sha1.hexdigest to sha1.digest

2008-04-06 Thread marek . rocki
Martin v. Löwis napisał(a):
> > How can convert string from sha1.hexdigest() to string that is the
> > same, like from sha1.digest()
>
> Use binascii.unhexlify.
>
> HTH,
> Martin

Or hexdigest_string.decode('hex')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can anyone help me?

2008-03-29 Thread marek . rocki
I love Paul's response.

[EMAIL PROTECTED] napisał(a):
> 

My crystal ball broke a few days ago due to overuse, but I recall that
OpenGL likes to have power-of-two texture sizes. If that doesn't work,
please trim down your code as far as possible (so that it still
displays the error) and post it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pass float array(list) parameter to C

2008-03-17 Thread marek . rocki
You can also do it with ctypes only; too bad it's not really well
documented. c_float is a type of a floating point number and it has *
operator defined, so that c_float*4 is a type of a 4-element array of
those numbers. So if you want to construct an array of floats from a
list of floats, you can do it like this:

from ctypes import c_float

x = [1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9]
float_array_type = c_float*len(x)
float_array = float_array_type(*x)
print float_array
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Want - but cannot get - a nested class to inherit from outer class

2008-03-08 Thread marek . rocki
Everybody has already explained why this doesn't work and a possible
"solution" using metaclasses was suggested. I tried to implement it,
ended up with monkey-patching __bases__, which is certainly an
abomination (will it be possible in python 3.0?) but seems to do the
trick.

class _InheritFromOuterClass(object):
""" This class is used as a marker. """
pass

class MetaFixInheritance(type):
""" This metaclass, along with ordinary class creation, changes base
of
all the inner classes (marked as inheriting from
_InheritFromOuterClass)
to the class being created. """
def __new__(self, name, bases, members):
result = type(name, bases, members)
for member in members.itervalues():
if isinstance(member, type) and issubclass(member,
_InheritFromOuterClass):
member.__bases__ = result,
return result

class Outer(object):
""" Test an inner class inheriting from the outer class. Inheritance
is
monkey-patched upon creation of the outer class. """
__metaclass__ = MetaFixInheritance
class Inner(_InheritFromOuterClass):
pass
def foo(self):
return 'Outer.foo()'

inner = Outer.Inner()
print 'Inner.foo() is in fact', inner.foo()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict.get and str.xsplit

2008-02-26 Thread marek . rocki
[EMAIL PROTECTED] napisał(a):
> [EMAIL PROTECTED]:
> > As for the original prooblem, why not use
> > defaultdict? I think it's the most idiomatic way to achieve what we
> > want. And also the fastest one, according to my quick-and-dirty tests:
>
> It adds the new keys, I can't accept that:

Right, my fault not noticing that. I experimented further with
__missing__ method and with "ask forgiveness" idiom (try... except
KeyError) and they were both noticeably slower. So checking with "in"
may be the most efficient way we have.

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


Re: dict.get and str.xsplit

2008-02-26 Thread marek . rocki
[EMAIL PROTECTED] napisał(a):
> It's slower still, despite doing the lookup two times half of the
> times (half keys are present in the test set). The "in" is an
> operator, it's faster than a method call, but I don't understand the
> other details. Now the difference between 1.78 and 1.56 is small
> enough, so probably now it's not much noticeable in practice in real
> programs, so my original argument is mostly dead now :-) In the code
> points where speed matters instead of a single line with a get() I can
> use two lines to create a local adict_get.

AFAIK, method/function call is generally slow in Python (similarly to
the dot attribute lookup). As for the original prooblem, why not use
defaultdict? I think it's the most idiomatic way to achieve what we
want. And also the fastest one, according to my quick-and-dirty tests:

from collections import defaultdict

def main(N, M):

# 

addict = defaultdict(lambda: None, adict)
t = clock()
for _ in xrange(M):
for k in keys1:
r = addict[k]
for k in keys2:
r = addict[k]
print round(clock() - t, 2), "s"

adict.get: 3.12 s
adict_get: 2.24 s
in: 1.62 s
defaultdict: 1.05 s
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parent instance attribute access

2008-02-25 Thread marek . rocki
Hello. Please post the minimal code that can be run and demonstrates
what's wrong. I tried the following and it works fine, args and kwargs
are visible:

class MyFactory(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs

class MyXmlFactory(MyFactory):
def __init__(self, *args, **kwargs):
MyFactory.__init__(self, *args, **kwargs)
def build(self, addr):
p = self.toto(*self.args, **self.kwargs)
return p
def toto(self, *args, **kwargs):
print 'args in toto:', args
print 'kwargs in toto:', kwargs
return 'ok'

print MyXmlFactory(1, 2, 3, four = 4, five = 5).build(None)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Floating point bug?

2008-02-13 Thread marek . rocki
Not a bug. All languages implementing floating point numbers have the
same issue. Some just decide to hide it from you. Please read
http://docs.python.org/tut/node16.html and particularly
http://docs.python.org/tut/node16.html#SECTION001610

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


Re: Encrypting a short string?

2008-02-11 Thread marek . rocki
erikcw napisal(a):
> But that can't be reversed, right? I'd like to be able to decrypt the
> data instead of having to store the hash in my database...
In such case it seems you have no choice but to use a symmetric
encryption algorithm - in other words, your original method. If the
strings are ~20 bytes long (3 DES blocks), then the base64-encoded
ciphertext will have 32 characters. In case of AES, that'll be up to
45 characters. Wouldn't such length be acceptable?

Paul Rubin napisal(a):
> 2. What happens if the user edits the subject line?
> Under normal security requirements you cannot do this. The ciphertext
> has to be longer than the plaintext since you don't want the opponent
> to be able to tell whether two plaintexts are the same. Therefore you
> have to attach some random padding to each plaintext. Also, you
> presumably want the ciphertext to be encoded as printing characters,
> while normally you'd treat the input as binary, so there is some
> further expansion.
If what erikcw is looking for is a cryptographically secure protocol,
there are more things to be careful about, like authentication or
replay attacks. But indeed, I'm wondering now what his use-case is.
> I'm using this encrypted string to identify emails from a
> user. (the string will be in the subject line of the email).
Why not use "From" field to identify emails from a particular user?

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


Re: Encrypting a short string?

2008-02-11 Thread marek . rocki
erikcw napisal(a):
> Hi,
>
> I'm trying to devise a scheme to encrypt/obfuscate a short string that
> basically contains the user's username and record number from the
> database.  I'm using this encrypted string to identify emails from a
> user. (the string will be in the subject line of the email).
>
> I'm trying to figure out which approach I should use to encrypt the
> data.  The string will be less than 20 characters long, and I'd like
> the encrypted version to be about the same size.
>
> I tried DES in the Crypto module, but the cipher text was to long to
> be usable in this case.
>
> Any suggestions?
>
> Thanks!

How about:
>>> hashlib.sha256("[EMAIL PROTECTED]|2937267834").hexdigest()[:20]

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


Re: Sine Wave Curve Fit Question

2008-01-30 Thread marek . rocki
Iain Mackay napisal(a):
> Python Folks
>
> I'm a newbie to Python and am looking for a library / function that can help
> me fit a 1D data vector to a sine  wave. I know the frequency of the wave,
> so its really only phase and amplitude information  I need.
>
>  I can't find anything in the most widely known libraries (they seem to be
> strong on polynomial fitting, but not, apparently, on trig functions) and I
> wondered if any one here had recommendations?
>
>  Something that implemented IEEE 1057 , or similar, would be perfect.
>
>
> TIA
> Iain

I'm not aware of any specialized library, but how about using numpy
and running FFT on your data? If you already know the frequency, you
can easily extract phase and scaled amplitude from the result.

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


Re: validate string is valid maths

2008-01-28 Thread marek . rocki
I decided to play with it a little bit, but take a different approach
than Steven. This seems actually one of the problems where regexp
might be a good solution.

import re

re_signednumber = r'([-+]?\d+)'
re_expression = '%s(?:([-+/*])[-+/*]*?%s)*' % (re_signednumber,
re_signednumber)
for test_case in ('3++8', '3++--*-9', '3++*/-9', '45--/**/+7',
'55/-**+-6**'):
print re.match(re_expression, test_case).groups()

Now you have two problems ;-)

One question: you write "in cases where multiple symbols conflict in
meaning (as '3++--*-9' the earliest valid symbols in the sequence
should be preserved". Aren't '++' the earliest valid symbols
(operation and sign)? It seems, instead, that in your test cases the
sign is always immediately preceding the number. My regexp
accommodates for that.

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


Re: Doesn't know what it wants

2008-01-26 Thread marek . rocki
> class vec2d(ctypes.Structure):
> """2d vector class, supports vector and scalar operators,
>and also provides a bunch of high level functions
>"""
> __slots__ = ['x', 'y']
>
> def __init__(self, x_or_pair, y = None):
>
> if y == None:
> self.x = x_or_pair[0]
> self.y = x_or_pair[1]
> else:
> self.x = x_or_pair
> self.y = y

I may be way off here, but why does vec2d inherit from
ctypes.Structure if it doesn't observe the protocol for Structures
(they're supposed to have _fields_, not __slots__)?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread marek . rocki
Nice challenge! I came up with something like this:

def find_repr(target, numbers):
org_reprs = dict((number, str(number)) for number in numbers)
curr_reprs = org_reprs
while target not in curr_reprs:
old_reprs, curr_reprs = curr_reprs, {}
for x in old_reprs:
for y in org_reprs:
repr_x, repr_y = old_reprs[x], old_reprs[y]
curr_reprs[x + y] = '(%s)+(%s)' % (repr_x, 
repr_y)
curr_reprs[x - y] = '(%s)-(%s)' % (repr_x, 
repr_y)
curr_reprs[x * y] = '(%s)*(%s)' % (repr_x, 
repr_y)
if y <> 0 and x % y == 0:
curr_reprs[x // y] = '(%s)/(%s)' % 
(repr_x, repr_y)
curr_reprs.update(old_reprs)
return curr_reprs[target]

print '21 =', find_repr(21, [2, 3, 5])
print '923 =', find_repr(923, [7, 8, 50, 8, 1, 3])

Unfortunately, this yields solutions that are a bit lispish (as in
'lots of superfluous parentheses' in the result). Nothing a simple
regex or two wouldn't fix ;-) And the solution found would be minimal
not with respect to the string length, but rather to the number of
operations to be performed.

Apart from that, I find it quite elegant. I'd like to know if it has
any flaws.

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


Re: Need help with a regular expression

2007-12-19 Thread marek . rocki
On 19 Gru, 13:08, Sharun <[EMAIL PROTECTED]> wrote:
> I am trying to find the substring starting with 'aaa', and ending with
> ddd OR fff. If ddd is found shouldnt the search stop? Shouldn't
> re5.search(str5).group(0) return 'aaa bbb\r\n ccc ddd' ?

The documentation for the re module (http://docs.python.org/lib/re-
syntax.html), tells you that the "*", "+", and "?" qualifiers are all
greedy; they match as much text as possible. What you are looking for
are the qualifiers "*?", "+?", "??". Your regex pattern might look
like this: "aaa.*?(ddd|fff)".

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


Re: how to convert 3 byte to float

2007-12-09 Thread marek . rocki
Mario M. Mueller napisał(a):
> Personally I would expect simple counts (since other seismic formats don't
> even think of using floats because most digitizers deliver counts). But I
> was told that there are floats inside.
>
> But if I assume counts I get some reasonable numbers out of the file.

I looked at the data and it seems to be 24-bit big-endian integers. I
even plotted it and the graph looks quite reasonable (though I have no
expertise in seismic data at all).

> But I'm experiencing some strange jumps in the data (seismic data is mostly
> quite smooth at 40 Hz sampling rate). I think I did some mistake in the
> byte order...

Probably. In your code sample, when you pad it to 32-bits, why are you
inserting every third byte, instead of the most significant one? Maybe
the following will work:

if sign:
s = struct.unpack('>i','%c%c%c%c' % (chr(0xFF),s0,s1,s2))[0]
else:
s = struct.unpack('>i','%c%c%c%c' % (chr(0x00),s0,s1,s2))[0]

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


Re: Magic class member variable initialization with lists

2007-11-14 Thread marek . rocki
This is the expected behaviour. The reference on classes (http://
docs.python.org/ref/class.html) says:

> Variables defined in the class definition are class variables;
> they are shared by all instances. To define instance variables,
> they must be given a value in the __init__() method or in
> another method. Both class and instance variables are
> accessible through the notation ``self.name'', and an instance
> variable hides a class variable with the same name when
> accessed in this way.

In your example, 'a' is a class variable, so it's shared by all
instances. 'b' is also a class variable, but in the __init__ method
you create an instance variable with the same name 'b', which takes
precedence over the class-level variable, so 'b' isn't shared.

I think what you need is:

class Proof:
def __init__(self):
self.a = []
self.b = []
# other things

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


Re: Transfer socket connection between programs

2007-11-12 Thread marek . rocki
JamesHoward napisa (a):
> Does anyone know any method to have one program, acting as a server
> transfer a socket connection to another program? I looked into
> transferring the connection via xml rpc to no avail. It seems to be a
> problem of getting access to a programs private memory space and
> giving another program access to that space.
>
> Thanks in advance,
> James Howard

Under Windows you may want to use WSADuplicateSocket WinAPI function +
a named pipe (for example) to transfer the obtained socket data from
one process to the other.

Hope that helped,
Marek

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


Re: Iteration for Factorials

2007-10-24 Thread marek . rocki
Tim Golden napisa (a):

> It's only a moment before the metaclass and
> the Twisted solution come along. :)

I couldn't resist. It's not as elegant as I hoped, but hey, at least
it memoizes the intermediate classes :-)


class fact_0(object):
value = 1

class fact_meta(object):
def __new__(cls, name, bases, attrs):
n = attrs['n']
class_name = 'fact_%i' % n
try:
return globals()[class_name]
except KeyError:
new_class = type(class_name, bases, {})
new_class.value = n * fact(n - 1).value
new_class.__str__ = lambda self: str(self.value)
globals()[class_name] = new_class
return new_class

class fact(object):
def __new__(self, n_):
class spanish_inquisition(object):
__metaclass__ = fact_meta
n = n_
return spanish_inquisition()

print fact(5)
print fact(3)
print fact(1)

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


Re: name space problem

2007-10-23 Thread marek . rocki
BBands napisa (a):
> An example:
>
> class classA:
> def __init__(self):
> self.b = 1
>
> def doStuff():
> some calcs
> a..b = 0
>
> a = classA():
> print a.b
> doStuff()
> print a.b
>
> That works as hoped, printing 1, 0.
>
> But, if I move doStuff to another module and:
>
> import doStuff
>
> class classA:
> def __init__(self):
> self.b = 1
>
> a = classA()
> print a.b
> doStuff.doStuff()
> print a.b
>
> I get a 1 printed and an error: NameError: global name 'a' is not
> defined
>
> I think this is a name space issue, but I can't grok it.
>
> Thanks in advance,
>
>  jab

Hello. Indeed the doStuff function in the doStuff module can't do 'a.b
= 0' (the double dot was just a typo, right?) because it doesn't know
anything about an object named a.

I think the right solution would be not to use 'a' as a global
variable, but rather to pass it as an explicit parameter to the
function.

In module doStuff:

def doStuff(a):
# some calcs
a.b = 0

In the main module:

import doStuff
# ...
doStuff.doStuff(a)

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


Re: Using arrays in Python - problems.

2007-10-23 Thread marek . rocki

attackwarningred napisa (a):

> The array F(n) is dynamically allocated earlier on and is sized with
> reference to shotcount, the number of iterations the model performs. The
> problem is I can't get something like this to run in Python using numpy,
> and for the size of the array to be sized dynamically with reference to
> the variable shotcount. I acknowledge that my knowledge of Python is
> still really basic (I only started learning it a few days ago) and I'm
> trying to get out of the Fortran programming mindset but I'm stuck and
> don't seem to be able to get any further. If anyone could help I'd be
> really grateful. Thanks very much in advance.

Hello. If you want your array to be dynamically resized at every loop
iteration, that might be quite inefficient. How about initialising it
with a required size?

F = numpy.array([0]*shotcount)
for n in xrange(shotcount):
F[n] = random.lognormvariate(F_mean, F_sd)

Hope that helps,
Marek

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


Re: generate list of partially accumulated values

2007-09-16 Thread marek . rocki
Those methods of computing partial sums seem to be O(n^2) or worse.
What's wrong with an ordinary loop?

for i in xrange(1, len(l)):
l[i] += l[i - 1]

And as for the list of objects:

ll = [l[i - 1].method(l[i]) for i in xrange(1, len(l))] + l[-1]

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


Re: To count number of quadruplets with sum = 0

2007-03-16 Thread marek . rocki
My attempt uses a different approach: create two sorted arrays, n^2
elements each; and then iterate over them looking for matching
elements (only one pass is required). I managed to get 58,2250612857 s
on my 1,7 MHz machine. It requires numpy for decent performance,
though.

import numpy
import time

def parse_input():
al, bl, cl, dl = [], [], [], []
for i in xrange(int(raw_input())):
a, b, c, d = map(int, raw_input().split())
al.append(a)
bl.append(b)
cl.append(c)
dl.append(d)
return al, bl, cl, dl

def count_zero_sums(al, bl, cl, dl):
n = len(al) # Assume others are equal

# Construct al extended (every element is repeated n times)
ale = numpy.array(al).repeat(n)
del al
# Construct bl extended (whole array is repeated n times)
ble = numpy.zeros((n*n,), int)
for i in xrange(n): ble[i*n:(i+1)*n] = bl
del bl
# Construct abl - sorted list of all sums of a, b for a, b in al, bl
abl = numpy.sort(ale + ble)
del ale, ble

# Construct cl extended (every element is repeated n times)
cle = numpy.array(cl).repeat(n)
del cl
# Construct dl extended (whole array is repeated n times)
dle = numpy.zeros((n*n,), int)
for i in xrange(n): dle[i*n:(i+1)*n] = dl
del dl
# Construct cdl - sorted list of all negated sums of a, b for a, b in
cl, dl
cdl = numpy.sort(-(cle + dle))
del cle, dle

# Iterate over arrays, count matching elements
result = 0
i, j = 0, 0
n = n*n
try:
while True:
while abl[i] < cdl[j]:
i += 1
while abl[i] > cdl[j]:
j += 1
if abl[i] == cdl[j]:
# Found matching sequences
ii = i + 1
while ii < n and abl[ii] == abl[i]: ii += 1
jj = j + 1
while jj < n and cdl[jj] == cdl[j]: jj += 1
result += (ii - i)*(jj - j)
i, j = ii, jj
except IndexError:
pass

return result

t = time.clock()
print count_zero_sums(*parse_input())
print time.clock() - t

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


Re: __cmp__ method

2006-06-14 Thread marek . rocki
Python documentation says:
>__cmp__( self, other)
> Called by comparison operations if rich comparison (see above) is not defined.
So it seems you have to redefine rich comparisons __lt__, __gt__,
__eq__ etc as well.

If all you need is change sorting order, why not use appropriate
parameters of sorted() function (cmp=... or key=...)?

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


Re: Linear regression in NumPy

2006-03-17 Thread marek . rocki
nikie napisal(a):
> I'm a little bit stuck with NumPy here, and neither the docs nor
> trial&error seems to lead me anywhere:
> I've got a set of data points (x/y-coordinates) and want to fit a
> straight line through them, using LMSE linear regression. Simple
> enough. I thought instead of looking up the formulas I'd just see if
> there isn't a NumPy function that does exactly this. What I found was
> "linear_least_squares", but I can't figure out what kind of parameters
> it expects: I tried passing it my array of X-coordinates and the array
> of Y-coordinates, but it complains that the first parameter should be
> two-dimensional. But well, my data is 1d. I guess I could pack the X/Y
> coordinates into one 2d-array, but then, what do I do with the second
> parameter?

Well, it works for me:

x = Matrix([[1, 1], [1, 2], [1, 3]])
y = Matrix([[1], [2], [4]])
print linear_least_squares(x, y)

Make sure the dimensions are right. X should be n*k, Y should (unless
you know what you are doing) be n*1. So the first dimension must be
equal.

If you wanted to:
y = Matrix([1, 2, 4])
it won't work because it'll have dimensions 1*3. You would have to
transpose it:
y = transpose(Matrix([1, 2, 4]))

Hope this helps.

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


Re: Adding method at runtime - problem with self

2006-03-06 Thread marek . rocki
Thank you all for your responses. That's exactly what I needed to know
- how to bind a function to an object so that it would comply with
standard calling syntax.

This is largely a theoretical issue; I just wanted to improve my
understanding of Python's OOP model. Using such features in real life
code would probably be classified either as excessive magic or bad
design. Oh well, at least now I can be an informed participant of
language holy wars :-)

Marek

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


Re: searching for the number of occurences of a string

2006-03-05 Thread marek . rocki
> hi;
> say i have a text file with a string ( say '(XYZ)') and I want to find
> the number of line where this string has occured. What is the best way
> to do that?

I would suggest:

# Read file contents
lines = file('filename.txt').readlines()
# Extract first line number containing 'XYZ' string
[(i, l) for (i, l) in enumerate(lines) if 'XYZ' in l][0][0]

Best regards,
Marek

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


Adding method at runtime - problem with self

2006-03-05 Thread marek . rocki
First of all, please don't flame me immediately. I did browse archives
and didn't see any solution to my problem.

Assume I want to add a method to an object at runtime. Yes, to an
object, not a class - because changing a class would have global
effects and I want to alter a particular object only. The following
approach fails:

class kla:
x = 1

def foo(self):
print self.x

k = kla()
k.foo = foo
k.foo()

I know where the problem is. The method shouldn't have 'self'
parameter. But how do I access object's attributes without it?

Best regards,

Marek

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