useless python - term rewriter

2011-11-18 Thread Sean McIlroy

## term rewriter (python 3.1.1)

def gettokens(string):
spaced = string.replace('(',' ( ').replace(')',' ) ')
return spaced.split()

def getterm(tokens):
if tokens[0] in '()':
term = []
assert tokens[0] == '('
tokens.pop(0)
while not tokens[0] == ')': term.append(getterm(tokens))
tokens.pop(0)
return term
return tokens.pop(0)

def parse(strg):
tokens = gettokens(strg)
term = getterm(tokens)
assert not tokens
return term

def unparse(term):
if type(term) == str: return term
subterms = [unparse(subterm) for subterm in term]
return '({})'.format(' '.join(subterms))

def atom(term):
return type(term) == str

def compound(term):
return type(term) == list

def variable(term):
return atom(term) and term[0].isupper()

def constant(term):
return atom(term) and not term[0].isupper()

def conformable(term1,term2):
return compound(term1) and compound(term2) and len(term1) ==
len(term2)

def getrule(string):
left, right = string.split('=')
return [parse(left), parse(right)]

def getrules(string):
nonblank = lambda substring: substring and not substring.isspace()
return [getrule(substring) for substring in string.splitlines() if
nonblank(substring)]

def substitute(bindings,term):
if constant(term): return term
if variable(term): return bindings.get(term,term)
return [substitute(bindings,subterm) for subterm in term]

def match(term,pattern):
from operator import concat
from functools import reduce
if variable(pattern): return [[pattern, term]]
if constant(pattern) and pattern == term: return []
if conformable(pattern,term):
matches = [match(subterm,subpattern) for subterm, subpattern
in zip(term,pattern)]
return reduce(concat,matches)
raise Exception

def rewrite(term,rule):
if type(rule) == dict:
function = rule[term[0]]
arguments = [int(subterm) for subterm in term[1:]]
return str(function(*arguments))
left, right = rule
bindings = dict(match(term,left))
return substitute(bindings,right)

def apply(rule,term):
try: return [rewrite(term,rule), True]
except:
if atom(term): return [term, False]
applications = [apply(rule,subterm) for subterm in term]
subterms = [subterm for subterm, change in applications]
changes  = [change  for subterm, change in applications]
return [subterms, any(changes)]

def normalize(term,rules):
while True:
changes = []
for rule in rules:
term, change = apply(rule,term)
changes.append(change)
if not any(changes): break
return term

def translate(rules):
string = input(' ')
if string and not string.isspace():
try:
term = parse(string)
normal = normalize(term,rules)
string = unparse(normal)
print(string)
except: print('parse error')

def interpret(equations):
import operator
rules = [vars(operator)] + getrules(equations)
while True:
try: translate(rules)
except KeyboardInterrupt:
print('end session')
break

example = 

(factorial 0) = 1
(factorial N) = (mul N (factorial (sub N 1)))

(fibonacci 0) = 0
(fibonacci 1) = 1
(fibonacci N) = (add (fibonacci (sub N 1)) (fibonacci (sub N 2)))



interpret(example)

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


Re: change text of a Tkinter Button by clicking it

2011-09-29 Thread Sean McIlroy
never mind. i found it.
-- 
http://mail.python.org/mailman/listinfo/python-list


change text of a Tkinter Button by clicking it

2011-09-28 Thread Sean McIlroy
hello

(how) can you change the text of a Tkinter Button by clicking it?
something like

def click(index): return lambda: buttons[index].text = 'hello'
buttons = [Button(root,command=click(index)) for index in
range(numbuttons)]

only with an attribute that Buttons actually have. sorry to have to
ask such a see-spot-run question. thanks if you can help.

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


midi file parser

2009-11-23 Thread Sean McIlroy



A Sequence is a list [FormatType, TimeDivision, Tracks] where

*) FormatType is in [0,1,2]
*) TimeDivision is either [TicksPerBeat] with TicksPerBeat in range
(2**15) or
   [FramesPerSecond, TicksPerFrame] with FramesPerSecond in range
(2**7)
   and TicksPerFrame in range(2**8)
*) Tracks is a list of Events

An Event is either a ChannelEvent or a MetaEvent.
A ChannelEvent is  [DeltaTime, EventType, Channel, Parameters]
and a MetaEvent is [DeltaTime, MetaType, Message] where

*) DeltaTime  is a nonnegative integer
*) EventType  is in range(7)
*) Channelis in range(2**4)
*) Parameters is a list with elements in range(2**7)
*) MetaType   is in range(2**7)
*) Messageis a string

The EventTypes and Parameters of ChannelEvents have the following
verbal handles:

EventTypeParameters

0 = NoteOff  [NoteNumber, Velocity]
1 = NoteOn   [NoteNumber, Velocity]
2 = NoteAftertouch   [NoteNumber, Amount]
3 = Controller   [ControllerType, Value]
4 = ProgramChange[ProgramNumber]
5 = ChannelAftertouch[Amount]
6 = PitchBend[ValueLSB, ValueMSB]



def concat(xs):
from itertools import chain
return list(chain(*xs))

def zeropadded(digits,minlength):
return [0]*(minlength-len(digits)) + digits

def noleadingzeros(digits):
while digits[0]==0 and len(digits)1: digits = digits[1:]
return digits

def number2digits(number,base):
digits = [number]
while digits[0]=base: digits[0:1] = [digits[0]//base, digits
[0]%base]
return digits

def digits2number(digits,base):
reversedigits = reversed(noleadingzeros(digits))
basepowers = [base**n for n in range(len(digits))]
return sum([x*y for (x,y) in zip(reversedigits,basepowers)])

def number2fixedlength(number,length):
return zeropadded(number2digits(number,2**8),length)

def fixedlength2number(digits):
return digits2number(digits,2**8)

def number2variablelength(number):
digits = number2digits(number,2**7)
padding = [2**7]*(len(digits)-1) + [0]
return [x+y for (x,y) in zip(digits,padding)]

def variablelength2number(variablelength):
padding = [2**7]*(len(variablelength)-1) + [0]
digits = [x-y for (x,y) in zip(variablelength,padding)]
return digits2number(digits,2**7)

def smallbyte(number):
return number  (2**7)

def getfixedlength(numbers,startindex,numbytes):
endindex = startindex + numbytes
return (endindex, numbers[startindex:endindex])

def getvariablelength(numbers,startindex):
index = startindex
while not smallbyte(numbers[index]): index = index + 1
endindex = index + 1
return (endindex, numbers[startindex:endindex])

def analyzetimedivision(numbers):
[byte1, byte2]  = numbers
indicator  = byte1 // (2**7)
firstbyte  = byte1 % (2**7)
secondbyte = byte2
if indicator==0:
ticksperbeat = (2**8) * firstbyte + secondbyte
return [ticksperbeat]
if indicator==1:
framespersecond = firstbyte
ticksperframe   = secondbyte
return [framespersecond, ticksperframe]

def synthesizetimedivision(numbers):
if len(numbers)==1:
[ticksperbeat] = numbers
firstbyte  = ticksperbeat // (2**8)
secondbyte = ticksperbeat  % (2**8)
indicator = 0
if len(numbers)==2:
[framespersecond, ticksperframe] = numbers
firstbyte  = framespersecond
secondbyte = ticksperframe
indicator = 1
byte1 = indicator * (2**7) + firstbyte
byte2 = secondbyte
return [byte1, byte2]

def analyzeheaderdata(numbers):
formattype   =  fixedlength2number(numbers[0:2])
numtracks=  fixedlength2number(numbers[2:4])
timedivision = analyzetimedivision(numbers[4:6])
return (formattype, numtracks, timedivision)

def synthesizeheaderdata(formattype,numtracks,timedivision):
formattype   = number2fixedlength(formattype, 2)
numtracks= number2fixedlength(numtracks,  2)
timedivision = synthesizetimedivision(timedivision)
return formattype + numtracks + timedivision

def analyzestatus(statusbyte):
number = statusbyte - (2**7)
eventtype = number // (2**4)
channel   = number  % (2**4)
return (eventtype, channel)

def synthesizestatus(eventtype,channel):
statusbyte = (2**7) + (2**4) * eventtype + channel
return [statusbyte]

def synthesizeevent(event):
if len(event)==4:
[deltatime, eventtype, channel, parameters] = event
return number2variablelength(deltatime) + synthesizestatus
(eventtype,channel) + parameters
if len(event)==3:
[deltatime, metatype, message] = event
quantifiedmessage = number2variablelength(len(message)) + [ord
(x) for x in message]
return number2variablelength(deltatime) + synthesizestatus
(7,15) + [metatype] + quantifiedmessage

def makechunk(identifier,numbers):
return identifier + number2fixedlength(len(numbers),4) + numbers

def 

Re: chr / ord

2009-11-03 Thread Sean McIlroy

thanks. that did the trick. in case anyone else is in the same boat as
myself, here are the relevant correspondences:

string - [int] bytes - [int]
---
--

lambda string: [ord(x) for x in string]   list
lambda ints: ''.join([chr(x) for x in ints])  bytes

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


chr / ord

2009-11-02 Thread Sean McIlroy
hello

how do i say chr and ord in the new python? the functions below
(which work in 2.6.6) show what i'm trying to do. thanks if you can
help.

def readbytes(filepath):
return [ord(x) for x in open(filepath,'rb').read()]

def writebytes(numbers,filepath):
open(filepath,'wb').write(''.join([chr(x) for x in numbers]))
-- 
http://mail.python.org/mailman/listinfo/python-list


midi file toolkit

2009-09-05 Thread Sean McIlroy
## python 2.6.2

from tkFileDialog import askopenfilename, askdirectory

def nowindow(function):
def windowless():
from Tkinter import Tk
Tk().withdraw()
return function()
return windowless

getfilename = nowindow(askopenfilename)
getdirectoryname = nowindow(askdirectory)

def haskellize(pathname):
return '\\'.join(pathname.split('/'))

def newname():
from time import time
return 'NAME_' + ''.join(str(time()).split('.'))

def mangle(name):
return '__' + name + '__'

def pathsafe(name):
return '_'.join(name.split('/'))

def changefilename(filename,directoryname=None,rewrite=lambda
name:name):
from os.path import split, splitext, join
dirname, filename = split(filename)
filename, extension = splitext(filename)
filename = rewrite(filename)
directoryname = directoryname or dirname
return join(directoryname,filename) + extension

def readbytes(filename):
return [ord(x) for x in file(filename,'rb').read()]

def writebytes(numbers,filename):
file(filename,'wb').write(''.join([chr(x) for x in numbers]))

def playbytes(numbers):
from os import startfile
filename = newname() + '.mid'
writebytes(numbers,filename)
startfile(filename)

def IfThenElse(criterion,optionTrue,optionFalse):
if bool(criterion)==True:  return optionTrue
if bool(criterion)==False: return optionFalse

def flatten(homogeneouslist):
from itertools import chain
while type(homogeneouslist[0])==list: homogeneouslist = list(chain
(*homogeneouslist))
return homogeneouslist

def number2digits(number,base):
digits = [number]
while digits[0]=base: digits[0:1] = [digits[0]//base, digits
[0]%base]
return digits

def digits2number(digits,base):
reversedigits = list(reversed(digits))
return sum([reversedigits[i]*(base**i) for i in range(len
(digits))])

def number2fixedlength(number,numbytes):
digits = number2digits(number,2**8)
numleadingzeros = IfThenElse(len(digits)numbytes,numbytes-len
(digits),0)
return [0]*numleadingzeros + digits

def fixedlength2number(digits):
while digits[0]==0: digits = digits[1:]
return digits2number(digits,2**8)

def number2variablelength(number):
digits = number2digits(number,2**7)
padding = [2**7]*(len(digits)-1) + [0]
return [x+y for (x,y) in zip(digits,padding)]

def variablelength2number(variablelength):
digits = [x-(2**7) for x in variablelength[:-1]] + variablelength
[-1:]
return digits2number(digits,2**7)

def getfixedlength(numbers,startindex,numbytes):
endindex = startindex + numbytes
return numbers[startindex:endindex], endindex

def getvariablelength(numbers,startindex):
index = startindex
while numbers[index]=(2**7): index = index + 1
endindex = index + 1
return numbers[startindex:endindex], endindex

headeridentifier   = [ord(x) for x in 'MThd']
trackidentifier= [ord(x) for x in 'MTrk']

eventtypes = range(2**3)
noteoff= eventtypes[0]  ## notenumber,
velocity   = parameters
noteon = eventtypes[1]  ## notenumber,
velocity   = parameters
noteaftertouch = eventtypes[2]  ## notenumber,
aftertouchvalue= parameters
controller = eventtypes[3]  ## controllernumber,
controllervalue  = parameters
programchange  = eventtypes[4]  ##
programnumber  = parameters[0]
channelaftertouch  = eventtypes[5]  ##
aftertouchvalue= parameters[0]
pitchbend  = eventtypes[6]  ## pitchvalueLSB,
pitchvalueMSB   = parameters
nonmidicontrol = eventtypes[7]

channels  = range(2**4)
systemexclusive   = channels[0]
meta  = channels[15]

def chunk(identifier,flatdata):
return identifier + number2fixedlength(len(flatdata),4) + flatdata

def analyzeheaderdata(data):
formattype   = data[0:2]
numtracks= data[2:4]
timedivision = data[4:6]
return [digits2number(x,2**8) for x in [formattype, numtracks,
timedivision]]

def synthesizeheaderdata(formattype,numtracks,timedivision):
datasegments = [number2fixedlength(x,2) for x in [formattype,
numtracks, timedivision]]
return datasegments[0] + datasegments[1] + datasegments[2]

def headerchunk(formattype,numtracks,timedivision):
return chunk(headeridentifier, synthesizeheaderdata(formattype,
numtracks, timedivision))

def trackchunk(events):
return chunk(trackidentifier,flatten(events))

def analyzestatus(status):
number = status[0]
eventtype = (number - 2**7) // (2**4)
channel = number % (2**4)
return eventtype, channel

def synthesizestatus(eventtype,channel):
number = (2**7) + eventtype*(2**4) + channel
return [number]

def midicontrolevent(deltatime,eventtype,channel,*parameters):
deltatime = number2variablelength(deltatime)
status = synthesizestatus(eventtype, channel)
return [deltatime, status, list(parameters)]

def nonmidicontrolevent(deltatime,messagedata,metatype=[]):

Re: tkinter: get filename of askopenfilename

2009-06-25 Thread Sean McIlroy

i think what he means is to put the global declaration inside the
function that assigns to filename:

def open_file_dialog():
global filename
filename = tkFileDialog.askopenfilename(filetypes=
[(allfiles,*)])

as it was, the function was creating a new variable called filename
and assigning to THAT (and then doing absolutely nothing with it).
with the above modification, the function understands that filename
refers to the global variable of that name, and that variable's value
does indeed get printed, but since the print statement comes before
root.mainloop() -- hence before the button gets pressed -- filename
gets printed before the function has assigned to it. this fact becomes
apparent if you initialize the variable with filename='blank' (for
example). putting the print statement after root.mainloop() doesn't
work either, since root.mainloop() keeps control from getting to the
print statement. the effect i think you want can be gotten from
putting the print statement into the function as well, so what you end
up with is this:

import Tkinter
import tkFileDialog

filename = 'uninitialized'

def open_file_dialog():
global filename
filename = tkFileDialog.askopenfilename(filetypes=
[(allfiles,*)])
print filename

root = Tkinter.Tk()
Tkinter.Button(root, text='Notch genes...',
command=open_file_dialog).pack()
root.mainloop()




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


tictactoe (reprise)

2008-06-28 Thread Sean McIlroy


AUTHOR: Sean McIlroy
LANGUAGE: Python 2.5
OVERVIEW: instances of tictactoeplayer play optimal tictactoe
SPECIALIZED TYPES: player={ex,oh}; empty={blank}; cell=player+empty;
board=[cell]
TYPE RELATIONS: bool(c)==True for any c in cell


ex, oh, blank = 'X', '0', ' '
linear = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],
[2,4,6]]
lines = lambda board: [[board[i] for i in x] for x in linear]
mover = lambda board: board.count(ex)==board.count(oh) and ex or oh
opponent = lambda player: player==ex and oh or ex
makesthreat = lambda player, cells: cells.count(blank)==1 and
opponent(player) not in cells
numthreats = lambda player, board: len([x for x in lines(board) if
makesthreat(player,x)])
haswon = lambda player, board: [player]*3 in lines(board)
marked = lambda board, index: [(board[i],mover(board))[i==index] for i
in range(9)]
display = lambda board: '\n\n' + '\n-+-+-\n'.join(['|'.join(board[3*i:
3*(i+1)]) for i in range(3)]) + '\n\n'
blankindices = lambda board: [i for i in range(9) if board[i]==blank]
isfinished = lambda board: blankindices(board)==[] or [ex]*3 in
lines(board) or [oh]*3 in lines(board)
numownthreats = lambda board: numthreats(mover(board),board)
numopponentsthreats = lambda board:
numthreats(opponent(mover(board)),board)
outcomevalue = lambda board: haswon(opponent(mover(board)),board) and
(-1) or haswon(mover(board),board) and (+1) or 0
assessment = lambda board: [outcomevalue(board),
(-1)*numopponentsthreats(board),(+1)*numownthreats(board)]
value = lambda board, index: blankindices(board) in [[],[index]] and
assessment(marked(board,index)) or \
 
min([assessment(marked(marked(board,index),i)) for i in
blankindices(board)if not i==index])
blankindexvalues = lambda board: [value(board,i) for i in
blankindices(board)]
analogisoptimal = lambda list1, list2, optimum: [x for (i,x) in
enumerate(list1) if list2[i]==optimum(list2)]
optimalblankindices = lambda board: blankindices(board) and
analogisoptimal(blankindices(board),blankindexvalues(board),max)
optimalmoves = lambda board: [marked(board,i) for i in
optimalblankindices(board)]
centergrabs = lambda board: [marked(board,i) for i in [4] if i in
blankindices(board)]
cornergrabs = lambda board: [marked(board,i) for i in [0,2,6,8] if i
in blankindices(board)]
tictactoemove = lambda board: len(blankindices(board)) in [8,9] and
(centergrabs(board) or cornergrabs(board))[0] or \
  optimalmoves(board) and
optimalmoves(board)[0] or isfinished(board) and board

class tictactoeplayer:
def __init__(self):
globals()['mark'] = self.mark
globals()['newgame'] = self.newgame
globals()['turn'] = self.turn
print 'ENTER mark(i) TO PLACE A MARK ON THE i-TH CELL'
print '123' + '\n' + '456' + '\n' + '789'
print 'ENTER newgame() TO START A NEW GAME'
print 'ENTER turn() TO GIVE UP YOUR TURN'
self.newgame()
def mark(self,offbyoneindex):
self.board = marked(self.board,offbyoneindex-1)
print 'your move:' + display(self.board)
self.turn()
def newgame(self):
self.board = [blank]*9
print 'new game:' + display(self.board)
def turn(self):
self.board = tictactoemove(self.board)
print 'my move:' + display(self.board)
--
http://mail.python.org/mailman/listinfo/python-list


override the interpreter's parser?

2008-04-12 Thread Sean McIlroy
hi all

i'd like to write a module that, when run in the interpreter, would
cause the interpreter to read certain strings that would normally be
rejected as syntax errors (strings beginning with the @ symbol, say)
and pass them on to an object defined in the aforementioned module.
where should i look to start finding out how to do this? thanks for
any help.

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


Re: override the interpreter's parser?

2008-04-12 Thread Sean McIlroy
never mind. i found it.
-- 
http://mail.python.org/mailman/listinfo/python-list


is this a bug? (python 2.3)

2007-03-09 Thread Sean McIlroy
hi all

when i run this code in python 2.3

##  BEGIN CODE
class warfare:
def __init__(self): self.pairs = [[0,0]]*2
def __str__(self): return str(self.pairs)
def setfirst (self,i,value): self.pairs[i][0] = value
def setsecond(self,i,value): self.pairs[i][1] = value

w = warfare()
print w
w.setfirst(0,'hello')
print w
##  END CODE

i get this result

##  BEGIN ACTUAL RESULT
[[0, 0], [0, 0]]
[['hello', 0], ['hello', 0]]
##  END ACTUAL RESULT

instead of the expected result

##  BEGIN EXPECTED RESULT
[[0, 0], [0, 0]]
[['hello', 0], [0, 0]]
##  END EXPECTED RESULT

is there a reasonable explanation for this behavior?

peace
stm

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


Re: is this a bug? (python 2.3)

2007-03-09 Thread Sean McIlroy
thanks


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


Re: Need an identity operator because lambda is too slow

2007-02-18 Thread Sean McIlroy
On Feb 17, 9:59 pm, Deron Meranda [EMAIL PROTECTED] wrote:
[snip]

this may be really dense, but i'm curious what's wrong with the
multiplexer idiom:

for item in some_sequence:
item2 = (not some_rare_condition and item) or \
(some_rare_condition and
some_transform_function(item))
. # more stuff

peace
stm

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


alias for data member of class instance?

2007-02-05 Thread Sean McIlroy
hi all

is there a way to do this ...

class clown:
def __init__(self):
self.x = 0
self.y = ALIAS(self.x) ## FEASIBLE ?

... so that you get results like this ...

krusty = clown()
krusty.x
 0
krusty.y
 0
krusty.x = 1
krusty.x
 1
krusty.y
 1

... ? thanks.

peace
stm

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


tkinter blues (greens, reds, ...)

2005-10-28 Thread Sean McIlroy
hi all

i recently wrote a script that implements a puzzle. the interface
mostly consists of a bunch of colored disks on a tkinter canvas. the
problem is that the disks change their colors in ways other than the
way they're supposed to. it certainly isn't just a bug in my script,
since i can sometimes change the color of certain disks just by taking
focus off of the window and then bringing it back again! does this
sound like some known bug in tkinter? and if so, is there a recommended
way of working around it? if it matters, i'm using python 2.3 under
windows 95. any advice will be much appreciated.

peace

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


Re: tkinter blues (greens, reds, ...)

2005-10-28 Thread Sean McIlroy
i'm using the canned colors (pink, orange, etc). should i try
changing to explicit color specifications to see if that makes a
difference? i'm not sure what the other guy meant by a soft toy, but
i take it the idea is to try and construct a correctness proof for the
script, and see what keeps it (the proof) from working. it's a sound
idea, of course, but the script is pretty darn straightforward, as you
can see (below). anyway, i'll let you know how it turns out.

peace




green  = 'green'

orange = 'orange'

pink   = 'pink'

yellow = 'yellow'

red= 'red'

blue   = 'blue'



fb = 'frontback'

ud = 'updown'

lr = 'leftright'



def select(x,a,b): return b[a.index(x)]

def frontback(orientation): return
select(orientation,[fb,ud,lr],[fb,lr,ud])

def updown(orientation): return
select(orientation,[fb,ud,lr],[lr,ud,fb])

def leftright(orientation): return
select(orientation,[fb,ud,lr],[ud,fb,lr])



class cell:

def __init__(self, circlecolor, pointercolor, orientation,
coordinates):

self.circlecolor  = circlecolor

self.pointercolor = pointercolor

self.orientation  = orientation

self.coordinates  = coordinates

def endpoint(self):

a,b = self.coordinates

if self.orientation==fb:

if abs(a)==1: return [2*a,2*b]

if abs(a)==2: return [a/2,b/2]

if self.orientation==ud: return [+a,-b]

if self.orientation==lr: return [-a,+b]



class cube:

def __init__(self):

self.ful = cell(green,  blue, fb, [-2,+2])

self.fur = cell(orange, blue, fb, [+2,+2])

self.fdl = cell(pink,   blue, fb, [-2,-2])

self.fdr = cell(yellow, blue, fb, [+2,-2])

self.bul = cell(green,  red,  fb, [-1,+1])

self.bur = cell(orange, red,  fb, [+1,+1])

self.bdl = cell(pink,   red,  fb, [-1,-1])

self.bdr = cell(yellow, red,  fb, [+1,-1])

self.cells =
[self.ful,self.fur,self.fdl,self.fdr,self.bul,self.bur,self.bdl,self.bdr]

def redraw(self,*cells):

for x in cells:

A = x.coordinates

B = x.endpoint()

erase(*A)

drawpointer(color=x.pointercolor,*(A+B))

drawcircle(color=x.circlecolor,*A)

def display(self):

self.redraw(*self.cells)

def cycle(self,a,b,c,d,funct):

x = d.circlecolor

y = d.pointercolor

z = funct(d.orientation)

d.circlecolor  = c.circlecolor

d.pointercolor = c.pointercolor

d.orientation  = funct(c.orientation)

c.circlecolor  = b.circlecolor

c.pointercolor = b.pointercolor

c.orientation  = funct(b.orientation)

b.circlecolor  = a.circlecolor

b.pointercolor = a.pointercolor

b.orientation  = funct(a.orientation)

a.circlecolor  = x

a.pointercolor = y

a.orientation  = z





rubik = cube()



def F1_():
rubik.cycle(rubik.ful,rubik.fur,rubik.fdr,rubik.fdl,frontback)

def F2_():
rubik.cycle(rubik.fdl,rubik.fdr,rubik.fur,rubik.ful,frontback)

def B1_():
rubik.cycle(rubik.bdl,rubik.bdr,rubik.bur,rubik.bul,frontback)

def B2_():
rubik.cycle(rubik.bul,rubik.bur,rubik.bdr,rubik.bdl,frontback)



def U1_(): rubik.cycle(rubik.bul,rubik.bur,rubik.fur,rubik.ful,updown)

def U2_(): rubik.cycle(rubik.ful,rubik.fur,rubik.bur,rubik.bul,updown)


def D1_(): rubik.cycle(rubik.bdl,rubik.bdr,rubik.fdr,rubik.fdl,updown)

def D2_(): rubik.cycle(rubik.fdl,rubik.fdr,rubik.bdr,rubik.bdl,updown)



def L1_():
rubik.cycle(rubik.ful,rubik.bul,rubik.bdl,rubik.fdl,leftright)

def L2_():
rubik.cycle(rubik.fdl,rubik.bdl,rubik.bul,rubik.ful,leftright)

def R1_():
rubik.cycle(rubik.fur,rubik.bur,rubik.bdr,rubik.fdr,leftright)

def R2_():
rubik.cycle(rubik.fdr,rubik.bdr,rubik.bur,rubik.fur,leftright)



def F1(): F1_(); rubik.redraw(rubik.ful,rubik.fur,rubik.fdr,rubik.fdl)

def F2(): F2_(); rubik.redraw(rubik.fdl,rubik.fdr,rubik.fur,rubik.ful)

def B1(): B1_(); rubik.redraw(rubik.bdl,rubik.bdr,rubik.bur,rubik.bul)

def B2(): B2_(); rubik.redraw(rubik.bul,rubik.bur,rubik.bdr,rubik.bdl)

def U1(): U1_(); rubik.redraw(rubik.bul,rubik.bur,rubik.fur,rubik.ful)

def U2(): U2_(); rubik.redraw(rubik.ful,rubik.fur,rubik.bur,rubik.bul)

def D1(): D1_(); rubik.redraw(rubik.bdl,rubik.bdr,rubik.fdr,rubik.fdl)

def D2(): D2_(); rubik.redraw(rubik.fdl,rubik.fdr,rubik.bdr,rubik.bdl)

def L1(): L1_(); rubik.redraw(rubik.ful,rubik.bul,rubik.bdl,rubik.fdl)

def L2(): L2_(); rubik.redraw(rubik.fdl,rubik.bdl,rubik.bul,rubik.ful)

def R1(): R1_(); rubik.redraw(rubik.fur,rubik.bur,rubik.bdr,rubik.fdr)

def R2(): R2_(); rubik.redraw(rubik.fdr,rubik.bdr,rubik.bur,rubik.fur)



def solve():

rubik.__init__()

rubik.display()



def scramble():

n = 15

from random import randint

f = [F1_,F2_,B1_,B2_,U1_,U2_,D1_,D2_,L1_,L2_,R1_,R2_]

for i in range(n): f[randint(0,11)]()

rubik.display()



canvaswidth = 380

canvasheight = 330



def 

Re: tkinter blues (greens, reds, ...)

2005-10-28 Thread Sean McIlroy
hi ron

changing from english words to hexadecimal numerals did the trick for
me, so everything's cool now. thanks for looking at it.

peace

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-01 Thread Sean McIlroy

Tom Anderson wrote:
snip
 So, if you're a pythonista who loves map and lambda, and disagrees with
 Guido, what's your background? Functional or not?

glad you asked. personally i don't know lisp (or scheme), but now i've
decided to learn it, because eventually it will no longer be possible
in python to pass functions as arguments or return them as values. the
education sig will have to change its motto to computer programming
for every C-programmer. until then hangers-on like myself can use
home-grown substitutes for the functional constructs (examples below),
but in my opinion the best thing is to migrate as soon as possible. the
real programmers are squeezing us out. now is the time to abandon
python for an intelligent language (macros! real conditional evaluation
instead of the and/or kluge!)

def LISTCOMP(f,s,g):
reval = []
for x in s:
if g(x):
reval.append(f(x))
return reval

def LAMBDA(arguments,value):
symbols = arguments.split(',')
def reval(*args):
for i in range(len(args)):
locals()[symbols[i]] = args[i]
return eval(value)
return reval

def MAP(f,s):
return LISTCOMP(f,s,LAMBDA('x','True'))

def FILTER(f,s):
return type(s)(LISTCOMP(LAMBDA('x','x'),s,f))

def REDUCE(f,s,t):
if not s: return t
return f(s[0],REDUCE(f,s[1:],t))

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-01 Thread Sean McIlroy
Peter Hansen wrote:
snip
 Sean, what gave you the impression this would change?

just inductive reasoning. i've been wrong before (like anyone who makes
that claim), and i'm a former python enthusiast, so my judgement must
be colored to some extent  by bitterness. maybe they have solid reasons
for scrapping the functional constructs. but to me it seems like
they're eliminating them just because they offend the sensibilities of
C-programmers. (i mean those stereotypical C-programmers, baffled by
recursion and the like, who don't want to be reproached with the fact
of their mathematical illiteracy.) if that's the case then list
comprehensions and/or first class functions are likely to be the next
target. even if they're not, it's pretty clear that python is leaving
its multiparadigmatic origins behind. do it our way, the pundits are
effectively saying, or get out. for my part, i'm getting out.

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


Re: Two questions on lambda:

2005-06-24 Thread Sean McIlroy
def PRINT(x): print x
f = lambda: PRINT(hello)

###

def let(x,y):
globals()[x] = y
return True

f = lambda x: let('y',x*x) and y+y

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


Re: Null String Variable

2005-05-16 Thread Sean McIlroy
well, somebody's already pointed out that bool(msg)==False iff msg==''.
i'm curious to know what's wrong with simply writing

if msg=='':
## do_something

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


Re: the bugs that try men's souls

2005-04-04 Thread Sean McIlroy
Jordan Rastrick [EMAIL PROTECTED] wrote in message news:[EMAIL 
PROTECTED]...

snip

Wow. I'd resigned myself to the task of reformulating my question in
an intelligent way, I stopped by just to leave a little note to the
effect that the thread wasn't dead, and I find out the question's been
answered. Thanks very much. I'll let you know how it turns out.

Peace,
Sean
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the bugs that try men's souls

2005-04-04 Thread Sean McIlroy
later
Wow again. I had a real V8 moment when I looked at your solution
(smacking my forhead, groaning ruefully, etc). You were right: my
intention was simply to hide the trivial cases from view; I completely
missed the fact that I was now testing for membership in a different
set. I should have remembered that python plays fair, and looked a
little harder to find my mistake.

Thanks again,
Sean
-- 
http://mail.python.org/mailman/listinfo/python-list


the bugs that try men's souls

2005-04-03 Thread Sean McIlroy
This needs some background so bear with me.

The problem: Suppose p is a permutation on {0...n} and t is the
transposition that switches x and y [x,y in {0...n}]. A stepup pair
(just a term I invented) for p is a pair (a,b) of integers in {0...n}
with ab. A stepup pair (a,b) for p is an inversion (standard term)
of p iff (p(a),p(b)) is NOT a stepup pair. Now, if {a,b}={x,y}, then
clearly (a,b) is an inversion of p iff it is NOT an inversion of pt
(functional composition). Also, if {a,b} and {x,y} are disjoint, then
(a,b) is an inversion of p iff it is an inversion of pt. The remaining
cases are the ones where {a,b} and {x,y} have a single element in
common, and of these, there are exactly as many inversions of p as
there are of pt, though in general it is not the same set of stepup
pairs for each function.

The code below represents my attempt to apply python toward getting
insight into why the number of inversions, with exactly one coordinate
in {x,y}, is the same for p and pt. The problem with the code is that
if, at the relevant line (MYSTERIOUSLY BROKEN), I use the
commented-out expression instead of the expression that's actually
there, then in some cases the script gives a DIFFERENT ANSWER to the
question whether a given pair is or is not an inversion of p
respectively pt.

I'd sure like to know what's going wrong with this. Here's the code:


## STEPUP PAIR: AN ORDERED PAIR (x,y) OF INTEGERS WITH xy

stepups = lambda n: n and stepups(n-1) + [[x,n] for x in range(n)] or
[]
xor = lambda x,y: (x and not y) or (y and not x)

def feedback(p,t):
## GIVEN A PERMUTATION f AND A STEPUP PAIR s WITH COORDINATES IN
THE RANGE OF f,
## SHOW THE INTEGER CASE OF THE PROPOSITION  f(s) IS A STEPUP
PAIR 
k = 18
moved = [i for i in range(len(t)) if t[i]i]
a, b = min(moved), max(moved)
n = len(p) - 1
s = stepups(n) ## MYSTERIOUSLY BROKEN: [x for x in stepups(n) if
xor(a in x,b in x)]
print '-'*k
print 'p: ' + str(range(n+1)) + '\n   ' + str(p)
print '-'*k
print 't = ' + str((a,b))
print '-'*k
print '%s %7s %3s' %('pair','p','pt') + '\n' + '-'*k
for [a,b] in s:
print '%s %5s %3s' %(str([a,b]),int([p[a],p[b]] in
s),int([p[t[a]],p[t[b]]] in s))
print '-'*k

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


Re: mysteriously nonfunctioning script - very simple

2005-03-27 Thread Sean McIlroy
Heiko Wundram [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]...

snip
 Why not try the following:
snip

I did try it, and it didn't work either. It appears there must be
something wrong with my computer, hopefully something benign. Thanks
anyway.

Peace,
STM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mysteriously nonfunctioning script - very simple

2005-03-26 Thread Sean McIlroy
Fair enough. Here's the verbose version:

##
from time import sleep,time,localtime

wakeuptime = (7,00) 
## I WANT TO BE WOKEN UP AT 7AM (FOR EXAMPLE)

onehourlater = (wakeuptime[0]+1, wakeuptime[1]) 
## ONE HOUR LATER THAN THAT IS 8AM

while not wakeuptime  localtime(time())[3:5]  onehourlater: sleep(3)
## CHECK THE CURRENT TIME EVERY 3 SECONDS, AND IF IT'S NOT BETWEEN
## 7AM AND 8AM, GO BACK TO SLEEP FOR ANOTHER 3 SECONDS

## CONTROL NEVER REACHES THIS POINT
##










Peter Hansen [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]...
 Sean McIlroy wrote:
  Can anybody help me make sense of the fact that the following script
  doesn't work? It's so simple I can't imagine what I'm missing. Any
  help will be much appreciated.
 
 Always post actual tracebacks of the problem, if
 indeed it is producing a traceback.  Do this always
 by *cut and paste*, not by retyping the text.  Make
 sure not to remove anything important, and make sure
 you are running the actual code you have posted here.
 
 Also always describe the problem in more detail than
 just doesn't work.  For all we know, the code runs
 fine but its output just doesn't suit you...
 
 -Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


mysteriously nonfunctioning script - very simple

2005-03-25 Thread Sean McIlroy
Can anybody help me make sense of the fact that the following script
doesn't work? It's so simple I can't imagine what I'm missing. Any
help will be much appreciated.

Peace,
STM


## ALARM CLOCK:
from time import sleep,time,localtime

wakeuptime = input('hours: '), input('minutes: ')
onehourlater = (wakeuptime[0]+1, wakeuptime[1])
while not wakeuptime  localtime(time())[3:5]  onehourlater:
sleep(3)
print 'PLAY A SOUND FILE'
-- 
http://mail.python.org/mailman/listinfo/python-list


how to use structured markup tools

2005-03-19 Thread Sean McIlroy

I'm dealing with XML files in which there are lots of tags of the
following form: abx/bcy/c/a (all of these letters are being
used as 'metalinguistic variables') Not all of the tags in the file are
of that form, but that's the only type of tag I'm interested in. (For
the insatiably curious, I'm talking about a conversation log from MSN
Messenger.) What I need to do is to pull out all the x's and y's in a
form I can use. In other words, from...

.
.
abx1/bcy1/c/a
.
.
abx2/bcy2/c/a
.
.
abx3/bcy3/c/a
.
.

...I would like to produce, for example,...

[ (x1,y1), (x2,y2), (x3,y3) ]

Now, I'm aware that there are extensive libraries for dealing with
marked-up text, but here's the thing: I think I have a reasonable
understanding of python, but I use it in a lisplike way, and in
particular I only know the rudiments of how classes work. So here's
what I'm asking for:

Can anybody give me a rough idea how to come to grips with the problem
described above? Or even (dare to dream) example code? Any help will be
very much appreciated.

Peace,
STM

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


Re: how to use structured markup tools

2005-03-19 Thread Sean McIlroy
Exactly what I was looking for. Thanks.

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


seeking tree-browser widget for use with Tkinter

2005-03-06 Thread Sean McIlroy
I'm looking for a widget, to be used with Tkinter, that displays a
tree whose leaves are strings. I thought there was something like that
in the Python Megawidgets, but when I look at the documentation
(http://pmw.sourceforge.net/doc/refindex.html), it doesn't seem to be
there. Any advice will be much appreciated.

Peace,
STM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: canvassing for assistance

2005-03-03 Thread Sean McIlroy
'scale' puts the lower-right corner of a bounding box where the
pointer is, while keeping the upper-left corner where it was before
(or, if the relevant item's coordinates aren't of bounding-box type,
the function does nothing).

Thanks for the link.

Peace,
STM


[EMAIL PROTECTED] [EMAIL PROTECTED] wrote in message news:[EMAIL 
PROTECTED]...
 Sean, nice work on canvasser!  One question: what is the purpose of
 'scale'?  I notice that if you have already drawn a line on the canvas,
 then 'scale' can be used to draw a straight-line element extending from
 the end of the previous freehand line, but if you start with a blank
 screen, 'scale' has no effect.
 
 BTW if you want to extend your app further, take a look at paint.py in
 the Vaults of Parnassus:
 http://py.vaults.ca/apyllo.py?i=173784088
 
 cheers,
 S
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String Replace Problem...

2005-02-28 Thread Sean McIlroy
I can't claim to have studied your problem in detail, but I get
reasonable results from the following:

filename = 'Errors.txt'
S = open(filename,'r').read().split()
f = lambda x: (x[0]=='@' and x[6:] + '.0') or (x=='/' and x + '\n') or
x
open(filename,'w').write(' '.join(map(f,S)))

HTH

-


[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]...
 Hello NG,
 
   probably this is a basic question, but I'm going crazy... I am unable
 to find an answer. Suppose that I have a file (that I called Errors.txt)
 which contains these lines:
 
 MULTIPLY
   'PERMX'  @PERMX1  1 34  1  20  1 6 /
   'PERMX'  @PERMX2  1 34  21 41  1 6 /
   'PERMX'  @PERMX3  1 34  1  20  7 14/
   'PERMX'  @PERMX4  1 34  21 41  7 14/
   'PERMX'  @PERMX5  1 34  1  20 15 26/
   'PERMX'  @PERMX6  1 34  21 41 15 26/
   'PERMX'  @PERMX7  1 34  1  20 27 28/
   'PERMX'  @PERMX8  1 34  21 41 27 28/
   'PERMX'  @PERMX9  1 34  1  20 29 34/
   'PERMX'  @PERMX10  1 34  21 41 29 34/
   'PERMX'  @PERMX11  1 34  1  20 35 42/
   'PERMX'  @PERMX12  1 34  21 41 35 42/
   'PERMX'  @PERMX13  1 34  1  20 43 53/
   'PERMX'  @PERMX14  1 34  21 41 43 53/
   'PERMX'  @PERMX15  1 34  1  20 54 61/
   'PERMX'  @PERMX16  1 34  21 41 54 61/
 /
 
 I would like to replace all the occurrencies of the keywords (beginning
 with the @ (AT) symbol) with some floating point value. As an example, this
 is what I do:
 
 #  --- CODE BEGIN
 
 import re
 import string
 
 # Set Some Dummy Parameter Values
 parametervalues = range(1, 17)
 
 # Open And Read The File With Keywords
 fid = open(Errors.txt,rt)
 onread = fid.read()
 fid.close()
 
 # Find All Keywords Starting with @ (AT)
 regex = re.compile([EMAIL PROTECTED], re.IGNORECASE)
 keywords = regex.findall(onread)
 
 counter = 0
 
 # Try To Replace The With Floats
 for keys in keywords:
 pars = parametervalues[counter]
 onread = string.replace(onread, keys, str(float(pars)))
 counter = counter + 1
 
 # Write A New File With Replaced Values
 fid = open(Errors_2.txt,wt)
 fid.write(onread)
 fid.close()
 
 #  --- CODE END
 
 
 Now, I you try to run this little script, you will see that for keywords
 starting from @PERMX10, the replaced values are WRONG. I don't know why,
 Python replace only the @PERMX1 leaving out the last char of the keyword
 (that are 0, 1, 2, 3, 4, 5, 6 ). These values are left in the file and I
 don't get the expected result.
 
 Does anyone have an explanation? What am I doing wrong?
 
 Thanks to you all for your help.
 
 Andrea.
 
 --
  Message for the recipient only, if received in error, please notify the
 sender and read http://www.eni.it/disclaimer/
-- 
http://mail.python.org/mailman/listinfo/python-list


canvassing for assistance

2005-02-28 Thread Sean McIlroy
Hi all!

I've written a utility for making diagrams. It could also be a good
environment for experimenting with a Tk canvas, so I'm including the
code here (see below). The problem is that, when I save a canvas and
include the resulting postscript file in a LaTeX document, I often
find that the right edge of the canvas has been cut off and/or that
there's a bunch of extra space at the bottom that forces the picture
to take up a whole page just by itself. The Introduction to Tkinter
lists a bunch of options for the Canvas postscript method, but it
doesn't say anything about the semantics of any of them, and there are
several that sound like they could be what I need. So, if anybody
knows how to exercise finer control over the Canvas postscript method,
I'd be grateful to hear about it.

Peace,
STM


###
## FRESH SHELL: import canvasser
## (so that text can be copied from the shell)
###

pencil = 1
eraser = 10
color = 'black'

def save():
from tkSimpleDialog import askstring
filename = askstring('save diagram','enter name of diagram: ') +
'.eps'

canvas.postscript(file=filename,width=100,height=100,pagewidth=100,pageheight=100)

def circle(x,y,radius=25,color=None): 
r = radius
return canvas.create_oval(x-r,y-r,x+r,y+r,fill=color)

#

__P__ = None
__I__ = None

def draw(event):   
global __P__
Q = [event.x,event.y]
canvas.create_line(__P__[0],__P__[1],Q[0],Q[1],width=pencil,fill=color)
__P__ = Q
   
def erase(event):
r = eraser
x,y = event.x,event.y
for x in canvas.find_overlapping(x-r,y-r,x+r,y+r):
canvas.delete(x)

def carry(event):
if __I__==None: return
C = canvas.coords(__I__)
x,y = event.x,event.y
if len(C)==2: canvas.coords(__I__,x,y)
else:
a,b = C[:2]
f = lambda i: ( i%2 and [y-b] or [x-a] ) [0]
D = [x,y] + [C[i] + f(i) for i in range(2,len(C))]
canvas.coords(__I__,*D)

def scale(event):
C = canvas.coords(__I__)
if len(C)4: return
canvas.coords(__I__,C[0],C[1],event.x,event.y)

def point(event):
codeArea.insert(INSERT,str(event.x) + ',' + str(event.y))

def item(event):
codeArea.insert(INSERT,str(canvas.find_closest(event.x,event.y)[0]))
  
def mouseDown(event):
global __P__,__I__
m = mode.get()
if   m==0: __P__ = [event.x,event.y]
elif m==2: point(event)
elif m==3: item(event)
elif m=4: __I__ = canvas.find_closest(event.x,event.y)

def mouseDrag(event):
m = mode.get()
if   m==0: draw(event)
elif m==1: erase(event)
elif m==4: carry(event)
elif m==5: scale(event)

def mouseUp(event): 
global __P__,__I__
__P__ = None
__I__ = None

def runCode(dummy):
x = codeArea.get()
y = [i for i in range(len(x)) if x[i]=='=' and
x[:i].count('(')==0]
z = y and x[:y[0]] + '=' + x[y[0]+1:] or x
print ' ' + z
try: exec z in globals() 
except: print 'ERROR'
codeArea.delete(0,END)

from Tkinter import *
print '*'*80
print 'REMINDER: canvas; pencil,eraser,color; save,circle'
print '*'*80 
root = Tk()
canvas = Canvas(root,background='white')
canvas.bind('Button-1',mouseDown)
canvas.bind('B1-Motion',mouseDrag)
canvas.bind('ButtonRelease-1',mouseUp)
canvas.pack(side=TOP,expand=1,fill=BOTH)
codeArea = Entry(root,font=6)
codeArea.pack(side=TOP,expand=1,fill=X)
codeArea.bind('Return',runCode)
ctrl = Frame(root)
mode = IntVar()
Radiobutton(ctrl,indicatoron=0,variable=mode,value=0,text='draw').pack(side=LEFT)
Radiobutton(ctrl,indicatoron=0,variable=mode,value=1,text='erase').pack(side=LEFT)
Radiobutton(ctrl,indicatoron=0,variable=mode,value=2,text='point').pack(side=LEFT)
Radiobutton(ctrl,indicatoron=0,variable=mode,value=3,text='item').pack(side=LEFT)
Radiobutton(ctrl,indicatoron=0,variable=mode,value=4,text='carry').pack(side=LEFT)
Radiobutton(ctrl,indicatoron=0,variable=mode,value=5,text='scale').pack(side=LEFT)
ctrl.pack(side=TOP,pady=10)
root.title('canvasser')
root.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String Replace Problem...

2005-02-28 Thread Sean McIlroy
Alright, now it's too much. It's not enough that you're eliminating it
from the language, you have to stigmatize the lambda as well. You
should take some time to reflect that not everybody thinks the same
way. Those of us who are mathematically inclined like the lambda
because it fits in well with the way we already think. And besides, it
amounts to an explicit declaration that the function in question has
no side effects. And besides, it adds flexibility to the language. Go
ahead and throw it away, but you're making python less accessible for
those of us whose central concern is something other than programming.
(Single line indeed!)
-- 
http://mail.python.org/mailman/listinfo/python-list


'modal dialogs' with Tkinter

2005-02-22 Thread Sean McIlroy
I'd like to have a function f such that, when f is invoked, a Tk
window w is presented in which a number of variables can be modified,
and f returns the values that are indicated by the relevant
menus/checkbuttons/etc at the time w gets closed. I've tried various
ways of doing this, without success. Any assistance would be greatly
appreciated.

Peace,
Sean McIlroy
-- 
http://mail.python.org/mailman/listinfo/python-list


two questions - no common theme

2005-02-09 Thread Sean McIlroy
And now for a pair of questions that are completely different:

1) I'd like to be able to bind callbacks to presses of the arrow
buttons on the keyboard. How do you say that in Tkinter?

2) The function 'listdir' in os.path returns a list of all the files
in the given directory - how do I get hold of a list of its
subdirectories?

Any help will be greatly appreciated.

Peace,
STM
-- 
http://mail.python.org/mailman/listinfo/python-list


Save the Canvas!

2005-02-01 Thread Sean McIlroy
I'd like to be able to save a Tkinter Canvas in a format other than
postscript (preferably gif). Is there a tool out there for
accomplishing that? Any help will be much appreciated.

Peace,
STM
-- 
http://mail.python.org/mailman/listinfo/python-list


reusing Tkinter Canvases

2005-01-14 Thread Sean McIlroy
I'd like to save one Tkinter Canvas in order to use it on another
Canvas later. The problem is that it gets saved as EPS but it needs to
be GIF to be reuseable. How can I convert that format?

Peace,
STM
-- 
http://mail.python.org/mailman/listinfo/python-list


unicode mystery

2005-01-10 Thread Sean McIlroy
I recently found out that unicode(\347, iso-8859-1) is the
lowercase c-with-cedilla, so I set out to round up the unicode numbers
of the extra characters you need for French, and I found them all just
fine EXCEPT for the o-e ligature (oeuvre, etc). I examined the unicode
characters from 0 to 900 without finding it; then I looked at
www.unicode.org but the numbers I got there (0152 and 0153) didn't
work. Can anybody put a help on me wrt this? (Do I need to give a
different value for the second parameter, maybe?)

Peace,
STM

PS: I'm considering looking into pyscript as a means of making
diagrams for inclusion in LaTeX documents. If anyone can share an
opinion about pyscript, I'm interested to hear it.

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


mysterious buggy behavior

2005-01-08 Thread Sean McIlroy
While fiddling with a little script I ran into a problem that baffles
me completely. Maybe I'm missing something completely obvious, and
somebody out there can diagnose the problem at a glance. Anyway,
that's the hope. Here's the code (it plays tic tac toe):



Something goes wrong with the time saver section of the function
makeMove. The section
needs to be there to ensure that the computer makes its move in a
reasonable amount of
time when it is making the first or the second move. That section of
code is so simple
that I can't even imagine what could be going wrong with it.



012
345
678


ex,oh,blank = range(3)
lines = [(0,3,6),(1,4,7),(2,5,8),(0,1,2),(3,4,5),(6,7,8),(0,4,8),(2,4,6)]
 
def subs(board,player,i):
b = board[:]
b[i] = player
return b   
  
def valMove(board):
winners = [x for x in (ex,oh) for L in lines if
board[L[0]]==board[L[1]]==board[L[2]]==x]
if winners: return winners[0]==ex and (+1,None) or (-1,None)
if board.count(blank)==0: return (0,None)
player = (oh,ex)[board.count(ex)==board.count(oh)]
optimal = (min,max)[player==ex]
blankIndices = [i for i in range(9) if board[i]==blank]
return optimal([(valMove(subs(board,player,i))[0],i) for i in
blankIndices])

BOARD = [blank]*9

def clickButton(i):
def f():
BOARD[i] = ex
(topButtons,midButtons,botButtons)[i//3][i%3]['text'] = 'X'
return f

def newGame():
BOARD = [blank]*9
for x in topButtons+midButtons+botButtons: x['text'] = ''

def makeMove():
i = None
## time saver
if BOARD.count(blank)=8:
for j in [4,0,2,6,8]:
if BOARD[j]==blank: i = j; break
## /time saver
if i==None: i = valMove(BOARD)[1]
BOARD[i] = oh
(topButtons,midButtons,botButtons)[i//3][i%3]['text'] = 'O'

from Tkinter import *

root = Tk()
###
topRow = Frame(master=root)
topButtons = [Button(master=topRow,width=1,command=clickButton(i)) for
i in range(3)]
###
midRow = Frame(master=root)
midButtons = [Button(master=midRow,width=1,command=clickButton(3+i))
for i in range(3)]
###
botRow = Frame(master=root)
botButtons = [Button(master=botRow,width=1,command=clickButton(6+i))
for i in range(3)]
###
map(lambda x: x.pack(side=TOP),[topRow,midRow,botRow])
map(lambda x: x.pack(side=LEFT),topButtons + midButtons + botButtons)
###
dummyRow = Frame(master=root)
placeHolder = Label(master=dummyRow,text='')
dummyRow.pack(side=TOP)
placeHolder.pack(side=TOP)
###
ctrlRow = Frame(master=root)
computerMoveButton = Button(master=ctrlRow,text='computer
move',command=makeMove)
newGameButton = Button(master=ctrlRow,text='new game',command=newGame)
ctrlRow.pack(side=TOP)
computerMoveButton.pack(side=TOP)
newGameButton.pack(side=TOP)
###
root.title('tic tac toe')
root.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


cosmetic Tkinter question

2004-12-26 Thread Sean McIlroy
I've got a bunch of Frames, all packed into the root window with
side=TOP, and in each Frame I've got a Checkbutton packed with
side=LEFT. I expected the Checkbuttons to be flush with the left edge
of the window, but they're not, and it looks a little gross. How do I
get them to align?
-- 
http://mail.python.org/mailman/listinfo/python-list


example code sought

2004-12-18 Thread Sean McIlroy
There's something quite simple I'd like to do, but I'm hampered by
lack of knowledge regarding Tkinter. If someone could help me out with
a snippet of maximally-simple code showing, in general terms, how to
do this, that would be really great. What I want to do is simply to
move a shape around on the screen using the mouse. I've looked at
Tkdnd.py but I can't seem to extract what I need from the more
involved stuff in there.

Peace,
STM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mean, median, and mode

2004-12-05 Thread Sean McIlroy
 mean = lambda x: sum(x)/len(x)
 median = lambda x: (max(x)-min(x))/2
 mode = lambda x: max([(x.count(y),y) for y in x])[1]

Robert Brewer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]...
 (now that we have a meaningful subject line)
 
 Alfred Canoy wrote:
I'm just new to programming and would like to ask for help..
  
   Build a module that contains three functions that do the following:
  
 a.. Compute the average of a list of numbers
 b.. Finds the statistical median value of a list of numbers
 c.. Finds the mode of a list of numbers
  
   Can you please give me clue how I should start solving the
   following problem
   below? Here's the source code that I did so far:
  
   # compute the average of a list of numbers:
   # Keeps asking for numbers until 0 is entered
   # Prints the average value
  
   count = 0
   sum = 0
   number = 1
  
   print 'Enter 0 to exit the loop'
   while number != 0:
   number = input ('Enter a number: ')
   count = count + 1
   sum = sum + number
   count = count -1
   print ' The average is:', sum/count
 
 For the mode, you might build a dictionary:
 
 freq = {}
 while number != 0:
 number = input ('Enter a number: ')
 count = count + 1
 sum = sum + number
 try:
 freq[number] += 1
 except KeyError:
 freq[number] = 1
 
 ...then you can check for the largest value in that dictionary:
 
 max = 0
 mode = None
 for k, v in freq.iteritems():
 if v  max:
 max = v
 mode = k
 
 I leave the rest in your capable hands... ;) Including the case where
 two numbers occur in equal frequencies. ;;)
 
 
 Robert Brewer
 MIS
 Amor Ministries
 [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list