A curious bit of code...

2014-02-13 Thread forman . simon
I ran across this and I thought there must be a better way of doing it, but 
then after further consideration I wasn't so sure.

  if key[:1] + key[-1:] == '<>': ...


Some possibilities that occurred to me:

  if key.startswith('<') and key.endswith('>'): ...

and:

  if (key[:1], key[-1:]) == ('<', '>'): ...


I haven't run these through a profiler yet, but it seems like the original 
might be the fastest after all?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A curious bit of code...

2014-02-13 Thread forman . simon
For the record I wasn't worried about the performance.  ;-)

It was for Tkinter event strings not markup tags.

I'm glad this was the time winner!

"key and key[0] == '<' and key[-1] == '>'"


Cheers to the folks who did the timings (and saved me from the trouble!)

Last but not least...  s[::len(s)-1]   omg!!?   ;-D
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A curious bit of code...

2014-02-14 Thread forman . simon
On Thursday, February 13, 2014 7:26:48 PM UTC-8, Ned Batchelder wrote:
> On 2/13/14 9:45 PM, forman.si...@gmail.com wrote:
> 
> > For the record I wasn't worried about the performance.  ;-)
> 
> >
> 
> > It was for Tkinter event strings not markup tags.
> 
> >
> 
> > I'm glad this was the time winner!
> 
> >
> 
> > "key and key[0] == '<' and key[-1] == '>'"
> 
> >
> 
> >
> 
> > Cheers to the folks who did the timings (and saved me from the trouble!)
> 
> >
> 
> > Last but not least...  s[::len(s)-1]   omg!!?   ;-D
> 
> >
> 
> 
> 
> If you aren't worried about performance, why are you choosing your code 
> 
> based on which is the fastest?  There are other characteristics 
> 
> (clarity, flexibility, robustness, ...) that could be more useful.


I guess I'm taking the word "worried" a little too seriously.

Back story: I am hoping to contribute to IDLE and am reading the code as a 
first step.  I came across that line of code (BTW, I was wrong: it is NOT 
processing Tkinter event strings but rather special " entries" in 
linecache.cache [1]) and had to resist the urge to change it to something more 
readable (to me.)  But when I thought about it I wasn't able to discern if any 
of the new versions would actually be enough of an improvement to justify 
changing it.

To be clear: I have no intention of modifying the IDLE codebase just for fairly 
trivial points like this one line.

The most satisfying (to me) of the possibilities is "if key and key[0] == '<' 
and key[-1] == '>':" in the dimensions, if you will, of readability and, uh, 
unsurprising-ness, and so I was pleased to learn that that was also the fastest.


(FWIW, it seems to me that whoever wrote that line was influenced by shell 
programming.  It's a shell sort of a trick to my eye.)


When writing Python code I *do* value "clarity, flexibility, robustness" and 
almost never worry about performance unless something is actually slow in a way 
that affects something..

Warm regards,
~Simon


[1] http://hg.python.org/cpython/file/3a1db0d2747e/Lib/idlelib/PyShell.py#l117
-- 
https://mail.python.org/mailman/listinfo/python-list


"Laws of Form" are a notation for the SK calculus, demo in Python.

2013-03-31 Thread forman . simon
I was investigating G. Spencer-Brown's Laws of Form[1] by implementing it
in Python.  You can represent the "marks" of LoF as datastructures in
Python composed entirely of tuples.

For example:
A mark: ()
A mark next to a mark: (), ()
A mark within a mark: ((),)
and so on...


It is known that the propositional calculus can be represented by the
"arithmetic of the mark". The two rules suffice:

((),) == nothing
() == (), ()

There are details, but essentially math and logic can be derived from the
behaviour of "the mark".


After reading "Every Bit Counts"[2] I spent some time trying to come up
with an EBC coding for the circle language (Laws of Form expressed as
tuples, See Burnett-Stuart's "The Markable Mark"[3])

With a little skull-sweat I found the following encoding:

  For the empty state (no mark) write '0'.

  Start at the left, if you encounter a boundary (one "side" of a mark, or
  the left, opening, parenthesis) write a '1'.

  Repeat for the contents of the mark, then the neighbors.

 _ -> 0
() -> 100
(), () -> 10100
 ((),) -> 11000
and so on...


I recognized these numbers as the patterns of the language called
'Iota'.[4]

Briefly, the SK combinators:

S = λx.λy.λz.xz(yz)
K = λx.λy.x

Or, in Python:

S = lambda x: lambda y: lambda z: x(z)(y(z))
K = lambda x: lambda y: x

can be used to define the combinator used to implement Iota:

i = λc.cSK

or,

i = lambda c: c(S)(K)


And the bitstrings are decoded like so: if you encounter '0' return i,
otherwise decode two terms and apply the first to the second.

In other words, the empty space, or '0', corresponds to i:

_ -> 0 -> i

and the mark () corresponds to i applied to itself:

() -> 100 -> i(i)

which is an Identity function I.

The S and K combinators can be "recovered" by application of i to itself
like so (this is Python code, note that I am able to use 'is' instead of
the weaker '==' operator.  The i combinator is actually recovering the
very same lambda functions used to create it.  Neat, eh?):

K is i(i(i(i))) is decode('1010100')
S is i(i(i(i(i is decode('101010100')

Where decode is defined (in Python) as:

decode = lambda path: _decode(path)[0]

def _decode(path):
  bit, path = path[0], path[1:]
  if bit == '0':
return i, path
  A, path = _decode(path)
  B, path = _decode(path)
  return A(B), path


(I should note that there is an interesting possibility of encoding the
tuples two ways: contents before neighbors (depth-first) or neighbors
before content (breadth-first). Here we look at the former.)

So, in "Laws of Form" K is ()()() and S is ()()()() and, amusingly, the
identity function I is ().

The term '(())foo' applies the identity function to foo, which matches the
behaviour of the (()) form in the Circle Arithmetic (()) == _ ("nothing".)


(())A ->  i(i)(A) -> I(A) -> A


I just discovered this (that the Laws of Form have a direct mapping to
the combinator calculus[5] by means of λc.cSK) and I haven't found anyone
else mentioning yet (although [6] might, I haven't worked my way all the
way through it yet.)

There are many interesting avenues to explore from here, and I personally
am just beginning, but this seems like something worth reporting.

Warm regards,
~Simon Peter Forman



[1] http://en.wikipedia.org/wiki/Laws_of_Form
[2] research.microsoft.com/en-us/people/dimitris/every-bit-counts.pdf
[3] http://www.markability.net/
[4] http://semarch.linguistics.fas.nyu.edu/barker/Iota/
[5] http://en.wikipedia.org/wiki/SKI_combinator_calculus have 
[6] 
http://memristors.memristics.com/Combinatory%20Logic%20and%20LoF/Combinatory%20Logic%20and%20the%20Laws%20of%20Form.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function definition

2006-06-19 Thread forman . simon
aarondesk wrote:
...
>
> Now I've tried putting the function declaration after the call but the
> program wouldn't work. Is there anyway to put function declarations at
> the end of the program, rather than putting them at the beginning,
> which is rather clunky?
>
> Thanks.
> Aaron

A function can call functions defined "below" it:

def a():
return b()

def b():
return 'foo'

print a() # prints 'foo'

because at runtime both functions exist in the current namespace.  But
module-level statements can't call functions defined below them because
the function objects haven't been created yet.  That's why you get a
NameError, the name 'b' won't been bound to anything until after the
def statement has been interpreted.

You can, of course, put your functions in another module.

Hope that helps,
~Simon

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


Re: returning index of minimum in a list of lists

2006-06-21 Thread forman . simon
[EMAIL PROTECTED] wrote:
> Hi all,
> Is there a simple python function to return the list index of the
> minimum entry in a list of lists?
> ie, for   [[3,3,3,3], [3,3,3,1], [3,3,3,3]]  to return 2,4.
> Or, same question but just for a list of numbers, not a list of lists.
> Thanks,
> Josh

One way to do this is to generate (value, index-in-main-list,
index-in-secondary-list) tuples and then just take the minimum.

def f(L):
'''Return indices of the first minimum value in a list of lists.'''
return min(
(n, i, j)
for i, L2 in enumerate(L)
for j, n in enumerate(L2)
)[1:]

L = [[3, 3, 3, 3], [3, 3, 3, 1], [3, 3, 3, 3]]

print f(L) # prints (1, 3)

Note: In python (and most other languages) indices begin at 0, so your
return values of (2, 4) wouldn't be correct.

For a list of numbers it's simpler.

L = [3, 3, 3, 1, 3, 3]
print min((n, i) for i, n in enumerate(L))[1] # prints 3

Hope this helps

~Simon

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


Re: str.isspace()

2006-09-03 Thread forman . simon
[EMAIL PROTECTED] wrote:
> Are you using the str.isspace() method? I don't use it, so if most
> people don't uses it, then it may be removed from Py 3.0.
>
> I usually need to know if a string contains some non-spaces (not space
> class chars). To do it I use something like:
>
> if aline.strip(): ...
>
> If you really need str.isspace() you may use (but so far I have never
> had to do this):
>
> if txt and not txt.strip(): ...
>
> Bye,
> bearophile

A quick check of code in my homedir showed that I've used it about 60
times (that's just in my own code, not work related code.)

In favor of removing it:
 * TOOWTDI

In favor of keeping it:

 * isspace() returns a Boolean, strip() returns a (newly-allocated)
string that's then just thrown away.

 * it's more obvious, "is space?" is exactly what I'm thinking when I
reach for isspace(),  it's never occurred to me to use strip() for this
task.  Compare:
if offset >= len(line) or line[offset].isspace():
if offset >= len(line) or line[offset].strip():

 * it's "symetrical" with the rest of the isfoo() string methods.
IMHO, it would be odd if it wasn't there.

My $0.02


Peace,
~Simon

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