import math, numpy as np, random as rand, re
# x, y are variables; z is the mode (or operation) that'll be done with "x" and "y".
def hyperoperatio():
#Variables
a = 1
var = []
x = input("Inserte número 1: ")
y = input("Inserte número 2: ")
z = input("Inserte modo: ")
log = input("¿Ud. prefiere que solo muestre las cifras del número? Sí (Y) o No (N): ")
#Formato de las variables (aunque en hyper más altas -de pentación en adelante-
#es mejor configurar todas las variables a formato int, ya que es más fácil de calcular).
x = float(x)
y = float(y)
z = int(z)
#Variables con valores específicos en las matemáticas, son importantes y les reservo un espacio.
specialvars = {
"pi" : math.pi,
"e" : math.e
}
print("x es igual a:",x,"e y es igual a:",y)
def hyper(x,y,z):
#Diccionarios con instrucciones para el programa (y además orienta al programador).
#Lo malo es que los resultados de los diccionarios son cargados totalmente aunque no sea
#necesario. Por ahora, no introduzca números muy grandes en "x" o "y". Ahora los str no son convertibles en float o int.
#Hiperoperaciones corrientes, volviéndose recursivo desde la tetración en adelante
operati = {
-4 : "\\1/((x**x)**y)",
-3 : "\\1/(x*y)",
-2 : "x/y",
-1 : "x-y",
1 : "x y",
2 : "x*y",
3 : "\\x**y",
4 : "\\(x**x)**y"
}
global a
#Elección de modos
if z == 0:
a = rand.randint(0,1)
elif z >= -4 and z <= 4:
a = float(operati[z])
print(a)
elif z == 5:
var.append(y)
y = x
b = int(operati[4])
y = var[0]
a = (b**b)**y
print(a)
print("El resultado es:",a)
hyper(x,y,z)
var.clear()
hyperoperatio()
How do I convert the elements of the dictionary "operati" so I can use the mathematical expressions as such? Without converting each meaning of that dictionary to a str, the program doesn't let me use the variables "x" and "y" with values that are over 5.
I also tried to use the backlash ("\") to solve that problem, but it didn't work. I don't know which character/s are causing the
CodePudding user response:
You need to evaluate the expressions. Right now you are trying to convert e.g. "x*y"
to a number, without plugging in the values. Instead, add eval
where necessary:
...
a = float(eval(operati[z]))
...
b = int(eval(operati[4]))
You also need to delete the backslashes in operati
.
CodePudding user response:
Cause
The reason you are getting an error is because you are trying to convert data to a type that it can't be converted to. To understand that, let's observe this line of code:
int("aaaa")
That wouldn't work, because there is no implementation of casting a string
to an int
.
Solutions
I'll suggest two solutions, but I really only recommend the first.
Create a function for each operation
Instead of keeping the mathematical representation of each operation as items of a dict
, create a function for each operation, that will accept x
and y
as paramaters. Something like:
def operation_add(x, y):
return x y
If you really like the idea of using a dict
, you could store references to these functions in a dict
like so:
operati = {
1: operation_add,
2: operation_mul
}
You'll just need to cast the input you get to the proper types before storing them into variables:
x = float(input("Inserte número 1: "))
Eval
Another option is to use the function eval
. This is generally considered a bad practice, especially when used with user input involved, but make your own choices. If you don't need your code to be secure or stable it can work.
What eval()
does is to take a string, and interpret it as if it were code.
For example:
x = 5
y = 2
print(str(eval(r"x * y")))
Would print out 10
.
If you insure that x
and y
have the proper values and are casted to the proper type, you could just do something like:
a = eval(operati[z])
print(a)