diff options
author | Pablo Moleri <pmoleri@PABLOMOLERI-PC.(none)> | 2009-07-02 21:26:54 (GMT) |
---|---|---|
committer | Pablo Moleri <pmoleri@PABLOMOLERI-PC.(none)> | 2009-07-02 21:26:54 (GMT) |
commit | 1d586f6b05d621f2233d0436f8c56bf8f34cb209 (patch) | |
tree | 35d06db60636eb7dc00162f5c8ab9b223601077e | |
parent | c655ca9d723fbf7b1a7f4ccd86681ff4be35923a (diff) |
Commit 2 2009-06-06
-rw-r--r-- | parentesis.activity/MANIFEST | 5 | ||||
-rw-r--r-- | parentesis.activity/TODO.txt | 348 | ||||
-rw-r--r-- | parentesis.activity/activity/activity-imageviewer.svg | 16 | ||||
-rw-r--r-- | parentesis.activity/activity/activity.info | 9 | ||||
-rw-r--r-- | parentesis.activity/activity/activity.info~ | 10 | ||||
-rw-r--r-- | parentesis.activity/interfaz.py | 143 | ||||
-rw-r--r-- | parentesis.activity/logica.py | 181 | ||||
-rw-r--r-- | parentesis.activity/parentesis.py | 121 | ||||
-rw-r--r-- | parentesis.activity/parentesis.py.bak | 121 | ||||
-rw-r--r-- | parentesis.activity/parserparentesis.py | 59 | ||||
-rwxr-xr-x | parentesis.activity/setup.py | 6 |
11 files changed, 1008 insertions, 11 deletions
diff --git a/parentesis.activity/MANIFEST b/parentesis.activity/MANIFEST new file mode 100644 index 0000000..0beecb7 --- /dev/null +++ b/parentesis.activity/MANIFEST @@ -0,0 +1,5 @@ +parentesis.py +logica.py +setup.py +activity/activity-imageviewer.svg +activity/activity.info diff --git a/parentesis.activity/TODO.txt b/parentesis.activity/TODO.txt new file mode 100644 index 0000000..aa136ed --- /dev/null +++ b/parentesis.activity/TODO.txt @@ -0,0 +1,348 @@ +#!/usr/bin/env python
+
+# example-start buttons buttons.py
+
+import pygtk
+pygtk.require('2.0')
+import gtk
+
+# Crea un boton con un parentesis y le da comportamiento de alternar el
+
+def crear_label_boton_paren(str):
+ boton = gtk.Button()
+ etiqueta = gtk.Label(str)
+ boton.add(etiqueta)
+
+ etiqueta.show()
+ boton.show()
+
+ return boton
+
+# Crea una label y la empaca en un boton
+# and pack it into a button
+def crear_label_boton(str):
+ button = gtk.Button();
+ etiqueta = gtk.Label(str)
+ button.add(etiqueta)
+ etiqueta.show()
+ button.show()
+
+ return button
+
+def devolver_par():
+ return (3,4)
+# Create a new hbox with an image and a label packed into it
+# and return the box.
+def xpm_label_box(parent, xpm_filename, label_text):
+ # Create box for xpm and label
+ box1 = gtk.HBox(False, 0)
+ box1.set_border_width(2)
+
+ # Now on to the image stuff
+ image = gtk.Image()
+ image.set_from_file(xpm_filename)
+
+ # Create a label for the button
+ label = gtk.Label(label_text)
+
+ # Pack the pixmap and label into the box
+ box1.pack_start(image, False, False, 3)
+ box1.pack_start(label, False, False, 3)
+
+ image.show()
+ label.show()
+ return box1
+
+class Controlador:
+ self.indiceCasoActual = 0
+ self.casoLista= generarCasos()
+ self.listaBotones = []
+
+ def generar_botones():
+ casoActual = casoLista[indiceCasoActual]
+ listaBotones = []
+ primerBoton = crear_label_boton("")
+ self.listaBotones.append(primerBoton)
+
+ for x in casoActual:
+ botonChar = crear_label_boton(x)
+ botonVacio = crear_label_boton("")
+ self.listaBotones.append(botonChar)
+ self.listaBotones.append(botonVacio)
+
+
+
+
+class Buttons:
+ # Our usual callback method
+ def callback(self, widget, data=None):
+ print "Hello again - %s was pressed" % data
+
+ def __init__(self):
+ # Create a new window
+ self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
+
+ self.window.set_title("Image'd Buttons!")
+ self.window.connect("destroy", lambda wid: gtk.main_quit())
+ self.window.connect("delete_event", lambda a1,a2:gtk.main_quit())
+ self.window.set_border_width(10)
+
+ cajaHorz = gtk.HBox(False, 0)
+
+ etiqueta = gtk.Label("PARENTESIS")
+ cajaVert = gtk.VBox(False, 0)
+ cajaVert.pack_start(etiqueta, True, True, 0)
+
+ cajaHor = gtk.HBox(False, 0)
+ button = gtk.Button()
+ button.connect("clicked", self.callback, "cool button")
+
+ self.listaBotones = []
+ boton = crear_label_boton("(")
+
+
+ cajaVert.pack_start(cajaHor, True, True, 0)
+ # This calls our box creating function
+ box1 = xpm_label_box(self.window, "info.xpm", "cool button")
+ button.add(box1)
+ cajaVert.pack_start(button, True, True, 0)
+ cajaVert.show()
+
+ box1.show()
+ button.show()
+ vscale = gtk.VScale(adjustment=None)
+ hscale = gtk.HScale(adjustment=None)
+
+
+ arrow = gtk.Arrow(gtk.ARROW_UP, gtk.SHADOW_IN)
+ arrow.show()
+ cajaVert.pack_start(arrow, True, True, 0)
+
+ botonIgual = crear_label_boton("=")
+ botonRes = crear_label_boton(str(eval("2+(3*4)+4") ) )
+ #cajaHorz.pack_start(botonPar1, True, True, 0)
+ #cajaHorz.pack_start(botonOprn1, True, True, 0)
+ #cajaHorz.pack_start(botonOprd1, True, True, 0)
+ #cajaHorz.pack_start(botonOprn2, True, True, 0)
+ #cajaHorz.pack_start(botonPar2, True, True, 0)
+ print self.listaBotones
+ cosita = botonRes.set_label("alfa")
+ print "la cista es", cosita
+
+
+ for x in "2+(3*4)+4":
+ self.listaBotones.append(x)
+ if x == "(" or x == ")":
+ boton = crear_label_boton(x)#crear_label_boton_paren(x)
+ print x, "parentesis"
+ else:
+ boton = crear_label_boton(x)
+ print x, "NO - parentesis"
+ cajaHorz.pack_start(boton, True, True,0)
+ cajaHorz.pack_start(botonIgual, True, True, 0)
+ cajaHorz.pack_start(botonRes, True, True, 0)
+
+
+ cajaVert.pack_start(cajaHorz, True, True, 0)
+ cajaHorz.show()
+ cajaVert.show()
+ # self.window.add(hscale)
+# hscale.show()
+
+
+ etiqueta.show()
+ self.window.add(cajaVert)
+ self.window.show()
+
+def main():
+ gtk.main()
+ return 0
+
+if __name__ == "__main__":
+ Buttons()
+ main()
+
+
+
+--------------
+import re
+import random
+import types
+
+### Version 0.3
+## modulo logico
+
+## Definicion a manopla para formulas de nivel 1
+pattern1 = "\S*\(\S*\+\S*\)\S*" # ( ... + ... ) al menos un mas en el medio
+pattern2 = "(\+\)|\*\)|\(\+|\(\*)" # ni (+ ni (* ni +) ni *)
+pattern3 = "^\(\w*\)$" # parentesis al principio y parentesis al final
+
+CANT_NUM = 6
+def imprimirConfiguracion():
+ """Usada para debug, muestra informacion del modulo"""
+ print "CONSTANTES"
+ print "CANT_NUM ", CANT_NUM
+ print "OPERANDOS", CANT_NUM - 1
+
+
+#Tal vez deba recibir un parametro NIVEL y en funcion de eso validar o no el string.
+def validarString(s):
+ """Si el string s es valido segun las convenciones lo devuelve, sino da none
+
+ Returns string"""
+ if re.search(pattern2, s):
+ return None
+ if re.search(pattern3, s):
+ return None
+ if re.search(pattern1, s):
+ return s
+ return None # en caso contrario devuelve nada
+
+
+##Funcion que testea las validaciones para todo el conjunto generado a mano de parentesis posibles
+## en un conjunto de 6 numeros
+def testearValidarStringNivelUno():
+ print "COMIENZA TEST DE VALIDACION DE LECTOR DE STRING..."
+ str1 = "(1*2+3)*4+5*6"
+ str2 = "(1*2+3*4)+5*6"
+ str3 = "(1*2+3*4+5)*6"
+ str4 = "1*(2+3)*4+5*6"
+ str5 = "1*(2+3*4)+5*6"
+ str6 = "1*(2+3*4+5)*6"
+ str7 = "1*(2+3*4+5*6)"
+ str8 = "1*2+(3*4+5)*6"
+ str9 = "1*2+(3*4+5*6)"
+ str10= "1*2+3*(4+5)*6"
+ str11= "1*2+3*(4+5*6)"
+ listaStr = [str1, str2, str3, str4, str5, str6, str7, str8, str9, str10, str11]
+ errores = [validarString(s) for s in listaStr]
+ if errores.count(None):
+ print "Hay errores de validacion!, verificar str1 .. str11"
+ else:
+ print " TEST OK"
+ print "FIN DEL TEST!"
+
+#notar los parametros opcionales ---remover---
+def generarListaNum(cant_num = CANT_NUM, rango_max = 9):
+ """genera una lista de tamano cant_num, con numeros entre 2 y rango_max
+ uqe no pueden estar repetidos"""
+ if cant_num + 1 > rango_max:
+ return None ### deberia de tirar una excepcion esto es MAL ESTILO TO DO
+ lista = []
+ while len(lista) < cant_num:
+ num = random.randint(2,rango_max)
+ if not lista.count(num):
+ lista.append(num)
+ return lista
+
+def generarListaOp(cant_op = CANT_NUM - 1):
+ """ genera una lista de largo cant_op alternando * y +, empezando por *"""
+ i = 1
+ lista = []
+ while i <= cant_op:
+ if i % 2:
+ lista.append('*')
+ else:
+ lista.append('+')
+ i += 1
+ return lista
+
+def alternarElementosLista(lst1, lst2):
+ """ alterna los elementos de las listas, generando una lista nueva
+ PRE: len(lst1) >= len(lst2)
+ Retorna la lista con los elementos alternados"""
+ lista = []
+ largo = len(lst2)
+ i = 0
+ while i < largo:
+ lista.append(lst1[i])
+ lista.append(lst2[i])
+ i += 1
+ #si quedan elementos en la lista 1 los agrego
+ largoNuevo = len(lst1)
+ while i < largoNuevo:
+ lista.append(lst1[i])
+ i += 1
+ return lista
+
+
+### TO DO : Discriminar segun niveles
+def generarCasos(cant_num = CANT_NUM, nivel = 1): ## TO DO!
+ """Recibe un numero y devuelve una lista con todos los casos posibles y con
+ los parentesis bien puestos"""
+ listaNum = generarListaNum()
+ listaOp = generarListaOp()
+ base = alternarElementosLista(listaNum, listaOp)
+ i1 = buscarProxNum(base, 0)
+ res = []
+ while i1 < len(base) : ## mientras tenga sentido poner un '('
+ lst = base[:]
+ lst.insert(i1, '(')
+ i2 = i1 + 6 # lo pongo en la posicion para insertar ')'
+ lst2 = lst[:]
+ lst2.insert(i2, ')')
+
+ aux = listaToString(lst2)
+ if validarString(aux) != None:
+ res.append(aux)
+
+
+ while i2 < len(base): ## chequear si es menor o menor e igual TO DO
+ lst2 = lst[:]
+ i2 += 2
+ lst2.insert(i2, ')')
+ aux = listaToString(lst2)
+ if validarString(aux) != None:
+ res.append(aux)
+
+ i1 = buscarProxNum(base, i1 + 1)
+
+ ## ( 1 * 2 + 3 * 4 + 5 * 6)
+ return res
+
+### Ejemplo de devolucion lista = ["(1*2+3)*4 + 5 * 6", "1*2+3 * (4+5)*6"]
+
+def listaToString(lst):
+ """Transforma una lista de cualquier cosa en un string conformado por la concatenacion de str de cada elemento """
+ texto = ''
+ for x in lst:
+ texto += str(x)
+ return texto
+
+def intToChar(o):
+ """Agarra un elemento, y si es un entero lo convierte a string, sino lo deja como esta"""
+ if types(o) == types.IntType:
+ return str(o)
+
+
+def buscarProxNum(lista, start = 0):
+ """Devuelve el proximo indice en la lista donde hay un numero
+ PRE: len(lista) > start
+ """
+
+ lst = lista[start:]
+ i = start
+ while len(lst) > 0 and type(lst.pop(0)) != types.IntType:
+ i += 1
+ return i
+
+
+### Pongo parentesis en el primer lugar que pueda --busco siguiente lugar con "numero a la derecha"
+ ### Busco indice para el segundo lugar --recorro lista
+ ### Si encuentro pongo y mando a testear/agregar
+ ### Si no encuentro indice, avanzo el primer indice
+ ###
+
+### [8, '*', 2, '+', 6, '*', 7, '+', 9, '*', 4]
+
+
+listaNum = generarListaNum()
+listaOp = generarListaOp()
+res = alternarElementosLista(listaNum, listaOp)
+
+if __name__ == "__main__":
+ testearValidarStringNivelUno()
+ lst = generarCasos()
+ for x in lst:
+ print x
+
diff --git a/parentesis.activity/activity/activity-imageviewer.svg b/parentesis.activity/activity/activity-imageviewer.svg new file mode 100644 index 0000000..7668033 --- /dev/null +++ b/parentesis.activity/activity/activity-imageviewer.svg @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [ + <!ENTITY fill_color "#FFFFFF"> + <!ENTITY stroke_color "#010101"> +]> +<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50"> + <rect x="3" y="7" width="44" height="36" style="fill:&fill_color;;stroke:&stroke_color;;stroke-width:3"/> + <polyline points="15,7 25,1 35,7" style="fill:none;;stroke:&stroke_color;;stroke-width:1.25"/> + <circle cx="14" cy="19" r="4.5" style="fill:&stroke_color;;stroke:&stroke_color;;stroke-width:1.5"/> + <polyline points="3,36 16,32 26,35" style="fill:none;;stroke:&stroke_color;;stroke-width:2.5"/> + <polyline points="15,43 37,28 47,34 47,43" style="fill:&stroke_color;;stroke:&stroke_color;;stroke-width:3"/> + <polyline points="22,41.5 35,30 27,41.5" style="fill:&fill_color;;stroke:none;;stroke-width:0"/> + <polyline points="26,23 28,25 30,23" style="fill:none;;stroke:&stroke_color;;stroke-width:.9"/> + <polyline points="31.2,20 33.5,17.7 35.8,20" style="fill:none;;stroke:&stroke_color;;stroke-width:1"/> + <polyline points="36,13 38.5,15.5 41,13" style="fill:none;;stroke:&stroke_color;;stroke-width:1"/> +</svg> diff --git a/parentesis.activity/activity/activity.info b/parentesis.activity/activity/activity.info new file mode 100644 index 0000000..405fe9f --- /dev/null +++ b/parentesis.activity/activity/activity.info @@ -0,0 +1,9 @@ +[Activity] +name = (P*A+R*E+N*T+E*S+I*S) +bundle_id = org.ceibaljam.parentesis +class = parentesis.Parentesis +icon = activity-imageviewer +activity_version = 1 +host_version = 1 +show_launcher = no +license = GPLv2+ diff --git a/parentesis.activity/activity/activity.info~ b/parentesis.activity/activity/activity.info~ new file mode 100644 index 0000000..47f4c0b --- /dev/null +++ b/parentesis.activity/activity/activity.info~ @@ -0,0 +1,10 @@ +[Activity] +name = Image Viewer +bundle_id = org.laptop.ImageViewerActivity +class = ImageViewerActivity.ImageViewerActivity +icon = activity-imageviewer +activity_version = 10 +host_version = 10 +show_launcher = no +mime_types = image/bmp;image/gif;image/jpeg;image/png;image/tiff +license = GPLv2+ diff --git a/parentesis.activity/interfaz.py b/parentesis.activity/interfaz.py new file mode 100644 index 0000000..07d3a98 --- /dev/null +++ b/parentesis.activity/interfaz.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python
+
+# example-start buttons buttons.py
+
+import pygtk
+pygtk.require('2.0')
+import gtk
+
+# Crea un boton con un parentesis y le da comportamiento de alternar el
+parentesis
+def crear_label_boton_paren(str):
+ boton = gtk.Button()
+ etiqueta = gtk.Label(str)
+ boton.add(etiqueta)
+
+ etiqueta.show()
+ boton.show()
+
+ return boton
+
+# Crea una label y la empaca en un boton
+# and pack it into a button
+def crear_label_boton(str):
+ button = gtk.Button();
+ etiqueta = gtk.Label(str)
+ button.add(etiqueta)
+ etiqueta.show()
+ button.show()
+
+ return button
+
+def devolver_par():
+ return (3,4)
+# Create a new hbox with an image and a label packed into it
+# and return the box.
+def xpm_label_box(parent, xpm_filename, label_text):
+ # Create box for xpm and label
+ box1 = gtk.HBox(False, 0)
+ box1.set_border_width(2)
+
+ # Now on to the image stuff
+ image = gtk.Image()
+ image.set_from_file(xpm_filename)
+
+ # Create a label for the button
+ label = gtk.Label(label_text)
+
+ # Pack the pixmap and label into the box
+ box1.pack_start(image, False, False, 3)
+ box1.pack_start(label, False, False, 3)
+
+ image.show()
+ label.show()
+ return box1
+
+
+
+class Buttons:
+ # Our usual callback method
+ def callback(self, widget, data=None):
+ print "Hello again - %s was pressed" % data
+
+ def __init__(self):
+ # Create a new window
+ self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
+
+ self.window.set_title("Image'd Buttons!")
+ self.window.connect("destroy", lambda wid: gtk.main_quit())
+ self.window.connect("delete_event", lambda a1,a2:gtk.main_quit())
+ self.window.set_border_width(10)
+
+ cajaHorz = gtk.HBox(False, 0)
+
+ etiqueta = gtk.Label("PARENTESIS")
+ cajaVert = gtk.VBox(False, 0)
+ cajaVert.pack_start(etiqueta, True, True, 0)
+
+ cajaHor = gtk.HBox(False, 0)
+ button = gtk.Button()
+ button.connect("clicked", self.callback, "cool button")
+
+ self.listaBotones = []
+ boton = crear_label_boton("(")
+
+
+ cajaVert.pack_start(cajaHor, True, True, 0)
+ # This calls our box creating function
+ box1 = xpm_label_box(self.window, "info.xpm", "cool button")
+ button.add(box1)
+ cajaVert.pack_start(button, True, True, 0)
+ cajaVert.show()
+
+ box1.show()
+ button.show()
+ vscale = gtk.VScale(adjustment=None)
+ hscale = gtk.HScale(adjustment=None)
+
+
+ arrow = gtk.Arrow(gtk.ARROW_UP, gtk.SHADOW_IN)
+ arrow.show()
+ cajaVert.pack_start(arrow, True, True, 0)
+
+ botonIgual = crear_label_boton("=")
+ botonRes = crear_label_boton(str(eval("2+(3*4)+4") ) )
+ #cajaHorz.pack_start(botonPar1, True, True, 0)
+ #cajaHorz.pack_start(botonOprn1, True, True, 0)
+ #cajaHorz.pack_start(botonOprd1, True, True, 0)
+ #cajaHorz.pack_start(botonOprn2, True, True, 0)
+ #cajaHorz.pack_start(botonPar2, True, True, 0)
+ print self.listaBotones
+ cosita = botonRes.set_label("alfa")
+ print "la cista es", cosita
+ for x in "2+(3*4)+4":
+ self.listaBotones.append(x)
+ if x == "(" or x == ")":
+ boton = crear_label_boton(x)#crear_label_boton_paren(x)
+ print x, "parentesis"
+ else:
+ boton = crear_label_boton(x)
+ print x, "NO - parentesis"
+ cajaHorz.pack_start(boton, True, True,0)
+ cajaHorz.pack_start(botonIgual, True, True, 0)
+ cajaHorz.pack_start(botonRes, True, True, 0)
+
+
+ cajaVert.pack_start(cajaHorz, True, True, 0)
+ cajaHorz.show()
+ cajaVert.show()
+ # self.window.add(hscale)
+# hscale.show()
+
+
+ etiqueta.show()
+ self.window.add(cajaVert)
+ self.window.show()
+
+def main():
+ gtk.main()
+ return 0
+
+if __name__ == "__main__":
+ Buttons()
+ main()
diff --git a/parentesis.activity/logica.py b/parentesis.activity/logica.py new file mode 100644 index 0000000..237ff41 --- /dev/null +++ b/parentesis.activity/logica.py @@ -0,0 +1,181 @@ +import re +import random +import types + +### Version 0.3 +## modulo logico + +## Definicion a manopla para formulas de nivel 1 +pattern1 = "\S*\(\S*\+\S*\)\S*" # ( ... + ... ) al menos un mas en el medio +pattern2 = "(\+\)|\*\)|\(\+|\(\*)" # ni (+ ni (* ni +) ni *) +pattern3 = "^\(\w*\)$" # parentesis al principio y parentesis al final + +CANT_NUM = 6 +def imprimirConfiguracion(): + """Usada para debug, muestra informacion del modulo""" + print "CONSTANTES" + print "CANT_NUM ", CANT_NUM + print "OPERANDOS", CANT_NUM - 1 + + +#Tal vez deba recibir un parametro NIVEL y en funcion de eso validar o no el string. +def validarString(s): + """Si el string s es valido segun las convenciones lo devuelve, sino da none + + Returns string""" + if re.search(pattern2, s): + return None + if re.search(pattern3, s): + return None + if re.search(pattern1, s): + return s + return None # en caso contrario devuelve nada + + +##Funcion que testea las validaciones para todo el conjunto generado a mano de parentesis posibles +## en un conjunto de 6 numeros +def testearValidarStringNivelUno(): + print "COMIENZA TEST DE VALIDACION DE LECTOR DE STRING..." + str1 = "(1*2+3)*4+5*6" + str2 = "(1*2+3*4)+5*6" + str3 = "(1*2+3*4+5)*6" + str4 = "1*(2+3)*4+5*6" + str5 = "1*(2+3*4)+5*6" + str6 = "1*(2+3*4+5)*6" + str7 = "1*(2+3*4+5*6)" + str8 = "1*2+(3*4+5)*6" + str9 = "1*2+(3*4+5*6)" + str10= "1*2+3*(4+5)*6" + str11= "1*2+3*(4+5*6)" + listaStr = [str1, str2, str3, str4, str5, str6, str7, str8, str9, str10, str11] + errores = [validarString(s) for s in listaStr] + if errores.count(None): + print "Hay errores de validacion!, verificar str1 .. str11" + else: + print " TEST OK" + print "FIN DEL TEST!" + +#notar los parametros opcionales ---remover--- +def generarListaNum(cant_num = CANT_NUM, rango_max = 9): + """genera una lista de tamano cant_num, con numeros entre 2 y rango_max + uqe no pueden estar repetidos""" + if cant_num + 1 > rango_max: + return None ### deberia de tirar una excepcion esto es MAL ESTILO TO DO + lista = [] + while len(lista) < cant_num: + num = random.randint(2,rango_max) + if not lista.count(num): + lista.append(num) + return lista + +def generarListaOp(cant_op = CANT_NUM - 1): + """ genera una lista de largo cant_op alternando * y +, empezando por *""" + i = 1 + lista = [] + while i <= cant_op: + if i % 2: + lista.append('*') + else: + lista.append('+') + i += 1 + return lista + +def alternarElementosLista(lst1, lst2): + """ alterna los elementos de las listas, generando una lista nueva + PRE: len(lst1) >= len(lst2) + Retorna la lista con los elementos alternados""" + lista = [] + largo = len(lst2) + i = 0 + while i < largo: + lista.append(lst1[i]) + lista.append(lst2[i]) + i += 1 + #si quedan elementos en la lista 1 los agrego + largoNuevo = len(lst1) + while i < largoNuevo: + lista.append(lst1[i]) + i += 1 + return lista + + +### TO DO : Discriminar segun niveles +def generarCasos(cant_num = CANT_NUM, nivel = 1): ## TO DO! + """Recibe un numero y devuelve una lista con todos los casos posibles y con + los parentesis bien puestos""" + listaNum = generarListaNum() + listaOp = generarListaOp() + base = alternarElementosLista(listaNum, listaOp) + i1 = buscarProxNum(base, 0) + res = [] + while i1 < len(base) : ## mientras tenga sentido poner un '(' + lst = base[:] + lst.insert(i1, '(') + i2 = i1 + 6 # lo pongo en la posicion para insertar ')' + lst2 = lst[:] + lst2.insert(i2, ')') + + aux = listaToString(lst2) + if validarString(aux) != None: + res.append(aux) + + + while i2 < len(base): ## chequear si es menor o menor e igual TO DO + lst2 = lst[:] + i2 += 2 + lst2.insert(i2, ')') + aux = listaToString(lst2) + if validarString(aux) != None: + res.append(aux) + + i1 = buscarProxNum(base, i1 + 1) + + ## ( 1 * 2 + 3 * 4 + 5 * 6) + return res + +### Ejemplo de devolucion lista = ["(1*2+3)*4 + 5 * 6", "1*2+3 * (4+5)*6"] + +def listaToString(lst): + """Transforma una lista de cualquier cosa en un string conformado por la concatenacion de str de cada elemento """ + texto = '' + for x in lst: + texto += str(x) + return texto + +def intToChar(o): + """Agarra un elemento, y si es un entero lo convierte a string, sino lo deja como esta""" + if types(o) == types.IntType: + return str(o) + + +def buscarProxNum(lista, start = 0): + """Devuelve el proximo indice en la lista donde hay un numero + PRE: len(lista) > start + """ + + lst = lista[start:] + i = start + while len(lst) > 0 and type(lst.pop(0)) != types.IntType: + i += 1 + return i + + +### Pongo parentesis en el primer lugar que pueda --busco siguiente lugar con "numero a la derecha" + ### Busco indice para el segundo lugar --recorro lista + ### Si encuentro pongo y mando a testear/agregar + ### Si no encuentro indice, avanzo el primer indice + ### + +### [8, '*', 2, '+', 6, '*', 7, '+', 9, '*', 4] + + +listaNum = generarListaNum() +listaOp = generarListaOp() +res = alternarElementosLista(listaNum, listaOp) + +if __name__ == "__main__": + testearValidarStringNivelUno() + lst = generarCasos() + for x in lst: + print x + diff --git a/parentesis.activity/parentesis.py b/parentesis.activity/parentesis.py new file mode 100644 index 0000000..21987c6 --- /dev/null +++ b/parentesis.activity/parentesis.py @@ -0,0 +1,121 @@ +# -*- encoding: UTF-8 -*- +import gtk +from sugar.activity.activity import Activity, ActivityToolbox +import logica + +ESTADO_VACIO = 0 +ESTADO_IZQ = 1 +ESTADO_DER = 2 + +IGUAL = "=" + +class Parentesis(Activity): + def __init__(self, handle): + Activity.__init__(self,handle) + + self.toolbox = ActivityToolbox(self) + self.set_toolbox(self.toolbox) + + self.vbox = gtk.VBox() + self.hbox = gtk.HBox() + self.msj = gtk.Label() + self.vbox.pack_start(self.msj) + self.vbox.pack_start(self.hbox) + self.set_canvas(self.vbox) + self.show_all() + + self.solucion_izquierdos = set() + self.solucion_derechos = set() + + self.problemas = logica.generarCasos() + self.MostrarProblema(self.problemas.pop()) + + def MostrarProblema(self, prob): + for w in self.hbox.get_children(): + self.hbox.remove(w) + + prob_str = prob + prob = list(prob) + pos = 0 + boton = self.crear_boton(pos) + self.agregar_widget(boton) + while pos < len(prob): + car = prob[pos] + if car == "(": + self.solucion_izquierdos.add(pos) + pos = pos + 1 + elif car == ")": + self.solucion_derechos.add(pos) + pos = pos + 1 + else: + car_etiqueta = gtk.Label(car) + self.agregar_widget(car_etiqueta) + pos = pos + 1 + boton = self.crear_boton(pos) + self.agregar_widget(boton) + + igual = self.crear_boton_igual() + self.agregar_widget(igual) + self.agregar_widget(gtk.Label(eval(prob_str))) + + def agregar_widget(self, widget): + ''' Agrega el boton a la lista de botones ''' + self.hbox.pack_start(widget) + widget.show() + + def crear_boton(self, pos): + boton = BotonParentesis(pos) + boton.connect('clicked', self.boton_activado) + return boton + + def crear_boton_igual(self): + boton = gtk.Button(IGUAL) + boton.connect('clicked', self.boton_igual_activado) + return boton + + def boton_activado(self, boton): + boton.iterarEstado() + + def boton_igual_activado(self, boton): + respuesta_izquierdos = set() + respuesta_derechos = set() + for widget in self.hbox.get_children(): + if isinstance(widget,BotonParentesis): + estado = widget.getEstado() + if estado == ESTADO_IZQ: + respuesta_izquierdos.add(widget.getPos()) + if estado == ESTADO_DER: + respuesta_derechos.add(widget.getPos()) + + if respuesta_izquierdos == self.solucion_izquierdos and respuesta_derechos == self.solucion_derechos: + self.msj.set_label("Muy Bien!") + self.MostrarProblema(self.problemas.pop()) + else: + self.msj.set_label("Incorrecto") + +class BotonParentesis(gtk.Button): + + def __init__(self, pos): + gtk.Button.__init__(self, "") + self._pos = pos + self._estado = ESTADO_VACIO + + def getPos(self): + return self._pos + + def setPos(self, pos): + self._pos = pos + + def iterarEstado(self): + if self._estado == ESTADO_VACIO: + self._estado = ESTADO_IZQ + self.set_label("(") + elif self._estado == ESTADO_IZQ: + self._estado = ESTADO_DER + self.set_label(")") + elif self._estado == ESTADO_DER: + self._estado = ESTADO_VACIO + self.set_label("") + + def getEstado(self): + return self._estado
\ No newline at end of file diff --git a/parentesis.activity/parentesis.py.bak b/parentesis.activity/parentesis.py.bak new file mode 100644 index 0000000..fef0bbb --- /dev/null +++ b/parentesis.activity/parentesis.py.bak @@ -0,0 +1,121 @@ +# -*- encoding: UTF-8 -*- +import gtk +from sugar.activity.activity import Activity, ActivityToolbox +import logica + +ESTADO_VACIO = 0 +ESTADO_IZQ = 1 +ESTADO_DER = 2 + +IGUAL = "=" + +class Parentesis(Activity): + def __init__(self, handle): + Activity.__init__(self,handle) + + self.toolbox = ActivityToolbox(self) + self.set_toolbox(self.toolbox) + + self.vbox = gtk.VBox() + self.hbox = gtk.HBox() + self.msj = gtk.Label() + self.vbox.pack_start(self.msj) + self.vbox.pack_start(self.hbox) + self.set_canvas(self.vbox) + self.show_all() + + self.solucion_izquierdos = set() + self.solucion_derechos = set() + + self.problemas = logica.generarCasos() + self.MostrarProblema(self.problemas.pop()) + + def MostrarProblema(self, prob): + for w in self.hbox.get_children(): + self.hbox.remove(w) + + prob_str = prob + prob = list(prob) + pos = 0 + boton = self.crear_boton(pos) + self.agregar_widget(boton) + while pos < len(prob): + car = prob[pos] + if car == "(": + self.solucion_izquierdos.add(pos) + pos = pos + 1 + elif car == ")": + self.solucion_derechos.add(pos) + pos = pos + 1 + else: + car_etiqueta = gtk.Label(car) + self.agregar_widget(car_etiqueta) + pos = pos + 1 + boton = self.crear_boton(pos) + self.agregar_widget(boton) + + igual = self.crear_boton_igual() + self.agregar_widget(igual) + self.agregar_widget(gtk.Label(eval('2+1'))) + + def agregar_widget(self, widget): + ''' Agrega el boton a la lista de botones ''' + self.hbox.pack_start(widget) + widget.show() + + def crear_boton(self, pos): + boton = BotonParentesis(pos) + boton.connect('clicked', self.boton_activado) + return boton + + def crear_boton_igual(self): + boton = gtk.Button(IGUAL) + boton.connect('clicked', self.boton_igual_activado) + return boton + + def boton_activado(self, boton): + boton.iterarEstado() + + def boton_igual_activado(self, boton): + respuesta_izquierdos = set() + respuesta_derechos = set() + for widget in self.hbox.get_children(): + if isinstance(widget,BotonParentesis): + estado = widget.getEstado() + if estado == ESTADO_IZQ: + respuesta_izquierdos.add(widget.getPos()) + if estado == ESTADO_DER: + respuesta_derechos.add(widget.getPos()) + + if respuesta_izquierdos == self.solucion_izquierdos and respuesta_derechos == self.solucion_derechos: + self.msj.set_label("Muy Bien!") + self.MostrarProblema(self.problemas.pop()) + else: + self.msj.set_label("Incorrecto") + +class BotonParentesis(gtk.Button): + + def __init__(self, pos): + gtk.Button.__init__(self, "") + self._pos = pos + self._estado = ESTADO_VACIO + + def getPos(self): + return self._pos + + def setPos(self, pos): + self._pos = pos + + def iterarEstado(self): + if self._estado == ESTADO_VACIO: + self._estado = ESTADO_IZQ + self.set_label("(") + elif self._estado == ESTADO_IZQ: + self._estado = ESTADO_DER + self.set_label(")") + elif self._estado == ESTADO_DER: + self._estado = ESTADO_VACIO + self.set_label("") + + def getEstado(self): + return self._estado
\ No newline at end of file diff --git a/parentesis.activity/parserparentesis.py b/parentesis.activity/parserparentesis.py index aefe5fe..237ff41 100644 --- a/parentesis.activity/parserparentesis.py +++ b/parentesis.activity/parserparentesis.py @@ -2,7 +2,7 @@ import re import random import types -### Version 0.2 +### Version 0.3 ## modulo logico ## Definicion a manopla para formulas de nivel 1 @@ -52,12 +52,9 @@ def testearValidarStringNivelUno(): if errores.count(None): print "Hay errores de validacion!, verificar str1 .. str11" else: - print "TEST OK" + print " TEST OK" print "FIN DEL TEST!" -if __name__ == "__main__": - testearValidarStringNivelUno(); - #notar los parametros opcionales ---remover--- def generarListaNum(cant_num = CANT_NUM, rango_max = 9): """genera una lista de tamano cant_num, con numeros entre 2 y rango_max @@ -102,19 +99,54 @@ def alternarElementosLista(lst1, lst2): return lista -### TOTALMENTE INCOMPLETA +### TO DO : Discriminar segun niveles def generarCasos(cant_num = CANT_NUM, nivel = 1): ## TO DO! """Recibe un numero y devuelve una lista con todos los casos posibles y con los parentesis bien puestos""" listaNum = generarListaNum() listaOp = generarListaOp() - res = alternarElementosLista(listaNum, listaOp) - - if nivel == 1: - return None - return None + base = alternarElementosLista(listaNum, listaOp) + i1 = buscarProxNum(base, 0) + res = [] + while i1 < len(base) : ## mientras tenga sentido poner un '(' + lst = base[:] + lst.insert(i1, '(') + i2 = i1 + 6 # lo pongo en la posicion para insertar ')' + lst2 = lst[:] + lst2.insert(i2, ')') + + aux = listaToString(lst2) + if validarString(aux) != None: + res.append(aux) + + + while i2 < len(base): ## chequear si es menor o menor e igual TO DO + lst2 = lst[:] + i2 += 2 + lst2.insert(i2, ')') + aux = listaToString(lst2) + if validarString(aux) != None: + res.append(aux) + + i1 = buscarProxNum(base, i1 + 1) + + ## ( 1 * 2 + 3 * 4 + 5 * 6) + return res + ### Ejemplo de devolucion lista = ["(1*2+3)*4 + 5 * 6", "1*2+3 * (4+5)*6"] +def listaToString(lst): + """Transforma una lista de cualquier cosa en un string conformado por la concatenacion de str de cada elemento """ + texto = '' + for x in lst: + texto += str(x) + return texto + +def intToChar(o): + """Agarra un elemento, y si es un entero lo convierte a string, sino lo deja como esta""" + if types(o) == types.IntType: + return str(o) + def buscarProxNum(lista, start = 0): """Devuelve el proximo indice en la lista donde hay un numero @@ -141,4 +173,9 @@ listaNum = generarListaNum() listaOp = generarListaOp() res = alternarElementosLista(listaNum, listaOp) +if __name__ == "__main__": + testearValidarStringNivelUno() + lst = generarCasos() + for x in lst: + print x diff --git a/parentesis.activity/setup.py b/parentesis.activity/setup.py new file mode 100755 index 0000000..e8d870b --- /dev/null +++ b/parentesis.activity/setup.py @@ -0,0 +1,6 @@ +#!/usr/bin/env python + +from sugar.activity import bundlebuilder + +bundlebuilder.start() + |