Scientific Programming in Python

Topic 1: Introduction and basic tools

Notebook created by Martín Villanueva - martin.villanueva@usm.cl - DI UTFSM - April 2017.

Actividad #1

Desarrolle una extensión de IPython (llamada 2to3_ext.py) implementando un cell magic, que reciba en su celda un código en Python2, lo transforme a código compatible con Python3, y finalmente lo ejecute en una instancia del IPython3, imprimiendo en la salida.

La entrega consiste en la extensión (2to3_ext.py) + un notebook de ejemplo de su extensión ejecutada con el código de a continuación:

a = float(raw_input("Ingrese a: "))
b = float(raw_input("Ingrese b: "))
c = float(raw_input("Ingrese c: "))

if a>(b+c) or b>(a+c) or c>(a+b):
    print "Ingrese un traingulo valido."
elif a==b and b==c:
    print "Triangulo equilatero."
elif a==b or b==c or a==c:
    print "Triangulo isoceles."
else:
    print "Triangulo escaleno."

Nota: Consideraremos que las únicas diferencias entre Python2 y Python3 son los print.

Solución

Solución propuesta por Sebastián Borquez


In [10]:
from IPython.core.magic import register_cell_magic

In [11]:
@register_cell_magic
def twotothree(line, cell):
    ip = get_ipython()
    original = cell.replace("raw_input","input").split("\n")
    python3 = ""
    for line in original:
        if "print" in line:
            line = line.replace("print ", "print(") + ")"
        python3 += line + "\n"
    ip.run_code(python3)

In [12]:
%%twotothree
a = float(raw_input("Ingrese a: "))
b = float(raw_input("Ingrese b: "))
c = float(raw_input("Ingrese c: "))

if a>(b+c) or b>(a+c) or c>(a+b):
    print "Ingrese un traingulo valido."
elif a==b and b==c:
    print "Triangulo equilatero."
elif a==b or b==c or a==c:
    print "Triangulo isoceles."
else:
    print "Triangulo escaleno."


Ingrese a: 2
Ingrese b: 3
Ingrese c: 4
Triangulo escaleno.