Python2 EOF when reading a line - python

everyone! I have this problem when I try to call a function that involves interaction with the user and I don't know what the problem is. The function that requires an input works perfect when separate from the other function.
I am using Jupyter Notebook [py2].
The function I am talking about is the following:
import numpy as np
import matplotlib.pyplot as plt
#Distribución Exponencial
def dist_exp():
a = int(raw_input("Ingrese Lambda: "))
b = int(raw_input("Ingrese la cantidad de numeros a generar: "))
beta = 1./a
exp = np.random.exponential((beta), b) #el primer valor es Beta (1/Lambda)
mediana_t = np.log(2)/(a*a)
print exp #imprime los números aleatorios generados
print "Estadísticos teóricos: ", "Minimo=0", " Maximo= infinito", " Media={}".format(beta), " Mediana={}".format(mediana_t), " Varianza={}".format(1/(a*a))
#imprime los estadísticos teóricos
print "Estadísticos muestrales: ", "Minimo={}".format(np.min(exp)), " Maximo={}".format(np.max(exp)), " Media={}".format(np.mean(exp)), " Mediana={}".format(np.median(exp)), " Varianza={}".format(np.var(exp))
#imprime los estadísticos muestrales
#bins son las clases para el histograma
if b<1000: #para los bins
bn = 20
else:
bn = 200
h = plt.hist(exp, bins=bn, normed=True) #bins son las clases para el histograma
plt.show() #despliega el histograma
I am calling this function (and 4 other similar functions) from the following:
from ipywidgets import widgets, interactive
from IPython.display import display
print "Ingrese la distribucion deseada. Las opciones son: Binomial, Exponencial, Geometrica, Lognormal y Triangular"
text = widgets.Text()
display(text)
def handle_submit(sender):
print(text.value)
if text.value == "Binomial":
return dist_bin()
elif text.value == "Exponencial":
return dist_exp()
elif text.value == "Geometrica":
return dist_geom()
elif text.value == "Lognormal":
return dist_log()
elif text.value == "Triangular":
return dist_tri()
else:
print "Por favor ingrese una distribucion valida. Ponga atencion a las opciones."
text.on_submit(handle_submit)
So, everytime the user types a valid String in the textbox, I need to perform a function, but I get this error instantly:
---------------------------------------------------------------------------
EOFError Traceback (most recent call last)
<ipython-input-8-1e49bbab45fa> in handle_submit(sender)
10 print(text.value)
11 if text.value == "Binomial":
---> 12 return dist_bin()
13 elif text.value == "Exponencial":
14 return dist_exp()
<ipython-input-5-081f517da431> in dist_bin()
1 #Distribución Binomial
2 def dist_bin():
----> 3 n = int(raw_input("Ingrese n: ")) #número de intentos
4 p = float(raw_input("Ingrese p: ")) #probabilidad de cada intento
5 num = int(raw_input("Ingrese la cantidad de numeros a generar: "))
EOFError: EOF when reading a line
I will appreciate any help.
Thank you all!

Related

Non-homogeneous Second Order Differential Equation With second member as a list

Hello. im working on a school project and im still a beginner in python. I need to solve this differential equation but I don't know how since the second member is a list.
This is my code
import numpy as np
import scipy.integrate as integr
t=np.linspace(0,799,96)
Q=np.array([60.50,113.93,199.59,292.04,376.85,459.97,526.13,570.23,604.16,623.66,626.21,627.06,628.75,622.81,600.76,585.50,582.10,567.69,536.30,501.53,489.66,480.33,451.49,411.63,372.61,332.75,304.76,276.77,242.85,211.47,178.39,107.99,24.03,-36.18,-13.28,19.79,39.3,51.17,41.84,28.27,18.94,19.79,27.42,38.45,40.99,31.66,21.48,12.16,4.52,-2.25,-10.73,-17.52,-20.06,-17.52,-14.98,-14.98,-16.67,-25.15,-34.48,-36.18,-31.94,-27.02,-24.30,-20.06,-16.67,-14.13,-15.82,-20.06,-26.85,-33.63,-37.03,-35.33,-31.09,-32.79,-37.03,-39.57,-40.42,-37.03,-31.09,-25.15,-26.85,-32.79,-40.42,-44.66,-46.36,-47.20,-48.05,-51.45,-53.99,-51.45,-44.66,-36.18,-29.39,-24.30,-20.06,-17.52]
)
Pmes=np.array([70.10,77.17,85.26,87.62,90.33,92.02,93.41,94.89,96.07,96.79,97.56,98.63,99.45,99.96,99.71,99.45,99.5,99.09,98.58,97.91,97.25,96.58,96.02,95.56,95.15,94.43,94.07,94.33,94.69,94.53,93.61,91.97,90.49,85.67,81.88,83.11,89.87,89.77,89.31,89.05,89.1,89.31,89.62,89.31,88.9,88.64,88.33,87.82,87.41,87.26,87.21,86.85,86.23,85.82,85.41,84.95,84.13,83.47,83.21,83.11,82.85,82.44,81.88,81.47,81.01,80.6,80.34,80.09,79.93,79.68,79.37,78.91,78.45,78.14,77.78,77.73,77.52,77.32,77.12,76.76,76.24,75.83,75.63,75.37,74.91,74.14,73.48,73.02,72.71,72.25,71.74,71.38,71.12,70.86,70.61,70.81])
#Conditions initiales
P0=70
dP0=70
#valeur de la résistance périphérique
Rp=0.63
#valeur de Rp4,Rc4,C4 et L pour le modèle de Windkessel à 4 éléments
Rc4=0.045
C4=2.53
L=0.0054
n=96
c=800/n
h=10**(-2)
A=np.array([[0,1],[-Rc4/(C4*L*Rp),-Rc4/L -1/(C4*Rp)]])
a=np.matrix(A)
#dérivée de Q
def D(F,i):
if i!=0 and i!=n-1:
return (F[i+1]-F[i-1])/2*h
elif i==0:
return (F[i+1]-F[i])/h
else:
return (F[i]-F[i-1])/h
#dérivé seconde de Q
def DD(F,i):
if i!=0 and i!=n-1:
return (F[i+1]+F[i-1]-2*F[i])/(2*(h*h))
elif i==0:
return (F[i+2]-2*F[i+1]+F[i])/(h*h)
else:
return (F[i]-2*F[i-1]+F[i-2])/(h*h)
#Second membre de l'équation différentielle
QQ=[DD(Q,i)*Rc4+D(Q,i)*(1/C4 +Rc4/(C4*Rp))+Q[i]*Rc4/(C4*Rp) for i in range(n)]
Pp=np.empty(n)
Pp[0]=[P0,dP0]
for i in range(n-1):
Pp[i+1]=c*a*np.matrix(Pp[i])+QQ[i]
P4WK=[Pp[i][0] for i in range(n)]
plt.plot(t,P4WK,'b',label='4WK')
plt.plot(t,Pmes,'g',label='Mesurée')
plt.title('La pression de l\'aorte ascedante pour le modèles de Windkessel à trois éléments')
plt.xlabel('temps(ms)')
plt.ylabel('Pression aortique(mmHg)')
plt.legend()
plt.grid()
plt.show()```

What am i doing wrong there? error "index out of range" trying to fill a list with lists

I want to do a list with lists inside, with a for and i get index out of range
I tryed with empleados.append() but it doesnt work
def main():
empleados=[]
for i in range(1):
empleados[i][0](input("Ingrese el Nombre: "))
empleados[i][1](input("Ingrese el Apellido: "))
empleados[i][2](int(input("Ingrese el Sueldo Base: ")))
empleados[i][3](int(input("Ingrese el AFP 1 o 2: ")))
empleados[i][4](datetime(int(input("Ingrese la Fecha de Ingreso(pulsa intro cada vez 2000 12 31): ")),int(input("/")),int(input("/"))))
empleados[i][5](int(input("Ingrese la cantidad de hijos que tiene: ")))
welcome to SO!
There's no list at empleados[0] to insert new values into. I find something like this is a little easier to read:
def main():
empleados=[]
for i in range(1):
empleado_nueva = []
empleado_nueva.append(input("Ingrese el Nombre: "))
empleado_nueva.append(input("Ingrese el Apellido: "))
empleado_nueva.append(int(input("Ingrese el Sueldo Base: ")))
empleado_nueva.append(int(input("Ingrese el AFP 1 o 2: ")))
empleado_nueva.append(datetime(int(input("Ingrese la Fecha de Ingreso(pulsa intro cada vez 2000 12 31): ")),int(input("/")),int(input("/"))))
empleado_nueva.append(int(input("Ingrese la cantidad de hijos que tiene: ")))
empleados.append(empleado_nueva)
return empleados
It's worth mentioning that the index-access pattern you're attempting (empleados[i][0] = ...) only works if there's something already at that index, for instance:
>>> x = []
>>> x[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> x = ['a', 'b', 'c']
>>> x[0] = 'd'
>>> x
['d', 'b', 'c']
So the append's are probably the best way to go.
The problem is you're trying use empleados[i] as a list with an existing index you can insert into, when at the moment, it's not.
You need to set up your variables a separate list and then append them. E.g.
def main():
empleados=[]
vars = [
input("Ingrese el Nombre: "),
input("Ingrese el Apellido: "),
int(input("Ingrese el Sueldo Base: ")),
int(input("Ingrese el AFP 1 o 2: ")),
datetime(int(input("Ingrese la Fecha de Ingreso(pulsa intro cada vez 2000 12 31): ")),int(input("/")),int(input("/"))),
int(input("Ingrese la cantidad de hijos que tiene: ")
empleados.append(vars)

ValueError: 0 is not in list when running this code

I'm currently working on a little side project yet having multiple issues. I'm reading a file within the folder where the project is that holds data for 10 users.
As for the code itself...it's pretty big.
def ouvrir_fichier(nomFichier):
""" Ne pas oublier les docstring
"""
try:
fp = open(nomFichier, 'r')
return fp
except:
return print("Le fichier n'existe pas. Veuillez réessayer.")
def lire_fichier(fp):
""" Ne pas oublier les docstring"""
# Lis n et initialise une liste vide --
# où il y a une liste vide pour chaque usager du réseau
# ensuite lis le reste du fichier et ajouter l'information à reseau
liste1 = fp.readlines()
n = int(liste1[0])
liste2 = liste1[1:]
reseau = [[] for i in range(n)]
for i in liste2:
i = i.replace("\n", "")
data = i.split(" ")
valeur1 = int(data[0])
valeur2 = int(data[1])
reseau[valeur1].append(valeur2)
reseau[valeur2].append(valeur1)
fp.close()
return reseau
def trouver_nombre_elements_communs_entre_listes(liste1, liste2):
""" Ne pas oublier les docstring"""
compteur_amis_commun = 0
for element in liste1:
if element in liste2:
compteur_amis_commun = compteur_amis_commun + 1
return compteur_amis_commun
def initialiser_matrice(n):
"""
Crée une matrice nxn, initialisée avec des zéros et retourne la matrice.
Args:
n (int): dimension de la matrice nxn
Returns:
matrice (list): matrice initialisée
"""
matrice = []
for ligne in range(n): # pour chacune des lignes dans n
matrice.append([]) # créer une ligne (liste) et l'initialiser à 0
for colonne in range(n):
matrice[ligne].append(0) # ajouter un 0 pour chaque n colonne
return matrice
def calculer_scores_similarite(reseau):
""" Ne pas oublier les docstring"""
n = len(reseau)
matrice_similarite = initialiser_matrice(n)
liste1 = []
liste2 = []
compteur_liste1 = 0
compteur_liste2 = 0
for element_liste1 in reseau:
liste1 = element_liste1
for element_liste2 in reseau:
liste2 = element_liste2
compteur_amis_commun = trouver_nombre_elements_communs_entre_listes(liste1, liste2)
matrice_similarite[compteur_liste1][compteur_liste2] = compteur_amis_commun
compteur_liste2 = compteur_liste2 + 1
compteur_liste1 = compteur_liste1 + 1
compteur_liste2 = 0
return matrice_similarite
def recommander(id_usager,reseau,matrice_similarite):
""" Ne pas oublier les docstring"""
usager_matrice = matrice_similarite.index(id_usager)
ami_recommande = matrice_similarite.index(max(usager_matrice))
max_value = max(matrice_similarite.index(usager_matrice))
if ami_recommande == id_usager:
max_value = max_value - 1
ami_recommande = matrice_similarite.index(max_value)
while True:
if ami_recommande == reseau.index(ami_recommande):
ami_recommande = reseau.index(max_value, ami_recommande + 1)
return True
return ami_recommande
def main():
nomFichier = input("Nom du fichier contenant le réseau: ")
reseau = lire_fichier(ouvrir_fichier(nomFichier))
n = len(reseau)
matrice_similarite = calculer_scores_similarite(reseau)
while True:
while True:
id_usager = int(input("Entrer l'ID de l'usager pour lequel vous voulez une recommandation (entre 0 et {}):".format(n)))
if 0 <= id_usager and id_usager < n:
calculer_scores_similarite(reseau)
print("Pour la personne" , id_usager , ", nous recommandons l'ami" , recommander(id_usager, reseau, matrice_similarite))
continue
else:
print("Erreur: l'usager doit être un nombre entier entre ", 0, "et", n - 1, "inclusivement.\n")
autreRecommandation = input("Voulez-vous une autre recommandation (oui/non)?")
if autreRecommandation.lower() == "oui":
return True
else:
print("Merci d'avoir utiliser le programme de recommandation d'amis.")
break
if __name__ == "__main__":
main()
Most of the content seems to be working fine until I get to part where I need to recommend a user identification. I'll try to work on the doc string as well in the meantime but I could totally use a little bit of help as to debug this. I tested most of the code on another .py project until I hit the function recommander
First Edit:
I did forget to apply the return. I changed it and it is now in the def. Now however...I seem to be having this error.
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\pydevd.py", line 1668, in <module>
main()
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\pydevd.py", line 1662, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\pydevd.py", line 1072, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/101136/PycharmProjects/tp2/TP2.py", line 132, in <module>
main()
File "C:/Users/101136/PycharmProjects/tp2/TP2.py", line 119, in main
print("Pour la personne" , id_usager , ", nous recommandons l'ami" , recommander(id_usager, reseau, matrice_similarite))
File "C:/Users/101136/PycharmProjects/tp2/TP2.py", line 89, in recommander
usager_matrice = matrice_similarite.index(id_usager)
ValueError: 0 is not in list
Also I'm wondering about a little something. The part where I ask for an input to define id_usager in the def main(), I was wondering if there was a way to also treat characters as well as integers. Integers, I got it covered with my code but if somebody wants to write boy instead of a number, it'll fail.
accessing element of list is done by list_name[index], list_name.index(element) returns the index of that element,if they are two in the list it returns the index of the first one, if the element is not there,it throws a ValueError: "element" is not in the list.
in your case
change
usager_matrice = matrice_similarite.index(id_usager)
to
usager_matrice =matrice_similarite[id_usager]
and other places you want to access element of a list using index
in the scond question from the comment, check if its numeric like this
id_usager =input("Entrer l'ID de l'usager pour lequel vous voulez une recommandation (entre 0 et {}):".format(n))
if not id_usager.isdigit():
continue
id_user=int(id_usager)
note that this will convert also floats into int

Pandas + Python: More efficient code

This is my code:
import pandas as pd
import os
import glob as g
archivos = g.glob('C:\Users\Desktop\*.csv')
for archiv in archivos:
nombre = os.path.splitext(archiv)[0]
df = pd.read_csv(archiv, sep=",")
d = pd.to_datetime(df['DATA_LEITURA'], format="%Y%m%d")
df['FECHA_LECTURA'] = d.dt.date
del df['DATA_LEITURA']
df['CONSUMO']=""
df['DIAS']=""
df["SUMDIAS"]=""
df["SUMCONS"]=""
df["CONSANUAL"] = ""
ordenado = df.sort_values(['NR_CPE','FECHA_LECTURA', 'HORA_LEITURA'], ascending=True)
##Agrupamos por el CPE
agrupado = ordenado.groupby('NR_CPE')
for name, group in agrupado: #Recorremos el grupo
indice = group.index.values
inicio = indice[0]
fin = indice[-1]
#Llenamos la primeras lectura de cada CPE, con esa lectura (porque no hay una lectura anterior)
ordenado.CONSUMO.loc[inicio] = 0
ordenado.DIAS.loc[inicio] = 0
cont=0
for i in indice: #Recorremos lo que hay dentro de los grupos, dentro de los CPES(lecturas)
if i > inicio and i <= fin :
cont=cont+1
consumo = ordenado.VALOR_LEITURA[indice[cont]] - ordenado.VALOR_LEITURA[indice[cont-1]]
dias = (ordenado.FECHA_LECTURA[indice[cont]] - ordenado.FECHA_LECTURA[indice[cont-1]]).days
ordenado.CONSUMO.loc[i] = consumo
ordenado.DIAS.loc[i] = dias
# Hago las sumatorias, el resultado es un objeto DataFrame
dias = agrupado['DIAS'].sum()
consu = agrupado['CONSUMO'].sum()
canu = (consu/dias) * 365
#Contador con el numero de courrencias de los campos A,B y C
conta=0
contb=0
contc=0
#Como es un DF, para recorrerlo tengo que iterar sobre ellos para hacer la comparacion
print "Grupos:"
for ind, sumdias in dias.iteritems():
if sumdias <= 180:
grupo = "A"
conta=conta+1
elif sumdias > 180 and sumdias <= 365:
grupo = "B"
contb=contb+1
elif sumdias > 365:
grupo = "C"
contc=contc+1
print "grupo A: " , conta
print "grupo B: " , contb
print "grupo C: " , contc
#Formateamos los campos para no mostrar todos los decimales
Fdias = dias.map('{:.0f}'.format)
Fcanu = canu.map('{:.2f}'.format)
frames = [Fdias, consu, Fcanu]
concat = pd.concat(frames,axis=1).replace(['inf','nan'],[0,0])
with open('C:\Users\Documents\RPE_PORTUGAL\Datos.csv','a') as f:
concat.to_csv(f,header=False,columns=['CPE','DIAS','CONSUMO','CONSUMO_ANUAL'])
try:
ordenado.to_excel(nombre+'.xls', columns=["NOME_DISTRITO",
"NR_CPE","MARCA_EQUIPAMENTO","NR_EQUIPAMENTO","VALOR_LEITURA","REGISTADOR","TIPO_REGISTADOR",
"TIPO_DADOS_RECOLHIDOS","FACTOR_MULTIPLICATIVO_FINAL","NR_DIGITOS_INTEIRO","UNIDADE_MEDIDA",
"TIPO_LEITURA","MOTIVO_LEITURA","ESTADO_LEITURA","HORA_LEITURA","FECHA_LECTURA","CONSUMO","DIAS"],
index=False)
print (archiv)
print ("===============================================")
print ("*****Se ha creado el archivo correctamente*****")
print ("===============================================")
except IOError:
print ("===================================================")
print ("¡¡¡¡¡Hubo un error en la escritura del archivo!!!!!")
print ("===================================================")
This takes a file where I have lectures of energy consumption from different dates for every light meter('NR_CPE') and do some calculations:
Calculate the energy consumption for every 'NR_CPE' by substracting the previous reading with the next one and the result put in a new column named 'CONSUMO'.
Calculate the number of days where I'v got a reading and sum up the number of days
Add the consumption for every 'NR_CPE' and calculate the anual consumption.
Finally I want to classify by number of days that every light meter('NR_CPE') has a lecture. A if it has less than 180 days, B between 180 and 1 year and C more than a year.
And finally write this result in two differents files.
Any idea of how should I re-code this to have the same output and be faster?
Thank you all.
BTW this is my dataset:
,NOME_DISTRITO,NR_CPE,MARCA_EQUIPAMENTO,NR_EQUIPAMENTO,VALOR_LEITURA,REGISTADOR,TIPO_REGISTADOR,TIPO_DADOS_RECOLHIDOS,FACTOR_MULTIPLICATIVO_FINAL,NR_DIGITOS_INTEIRO,UNIDADE_MEDIDA,TIPO_LEITURA,MOTIVO_LEITURA,ESTADO_LEITURA,DATA_LEITURA,HORA_LEITURA
0,GUARDA,A002000642VW,101,1865411,4834,001,S,1,1,4,kWh,1,1,A,20150629,205600
1,GUARDA,A002000642VW,101,1865411,4834,001,S,1,1,4,kWh,2,2,A,20160218,123300
2,GUARDA,A002000642VJ,122,204534,25083,001,S,1,1,5,kWh,1,1,A,20150629,205700
3,GUARDA,A002000642VJ,122,204534,27536,001,S,1,1,5,kWh,2,2,A,20160218,123200
4,GUARDA,A002000642HR,101,1383899,11734,001,S,1,1,5,kWh,1,1,A,20150629,205600
5,GUARDA,A002000642HR,101,1383899,11800,001,S,1,1,5,kWh,2,2,A,20160218,123000
6,GUARDA,A002000995VM,101,97706436,12158,001,S,1,1,5,kWh,1,3,A,20150713,155300
7,GUARDA,A002000995VM,101,97706436,12163,001,S,1,1,5,kWh,2,2,A,20160129,162300
8,GUARDA,A002000995VM,101,97706436,12163,001,S,1,1,5,kWh,2,2,A,20160202,195800
9,GUARDA,A2000995VM,101,97706436,12163,001,S,1,1,5,kWh,1,3,A,20160404,145200
10,GUARDA,A002000996LV,168,5011703276,3567,001,V,1,1,6,kWh,1,1,A,20150528,205900
11,GUARDA,A02000996LV,168,5011703276,3697,001,V,1,1,6,kWh,2,2,A,20150929,163500
12,GUARDA,A02000996LV,168,5011703276,1287,002,P,1,1,6,kWh,1,1,A,20150528,205900
Generally you want to avoid for loops in pandas.
For example, the first loop where you calculate total consumption and days could be rewritten as a groupby apply something like:
def last_minus_first(df):
columns_of_interest = df[['VALOR_LEITURA', 'days']]
diff = columns_of_interest.iloc[-1] - columns_of_interest.iloc[0]
return diff
df['date'] = pd.to_datetime(df['DATA_LEITURA'], format="%Y%m%d")
df['days'] = (df['date'] - pd.datetime(1970,1,1)).dt.days # create days column
df.groupby('NR_CPE').apply(last_minus_first)
(btw I don't understand why you are subtracting each entry from the previous, surely for meter readings this is the same as last-first?)
Then given the result of the above as consumption, you can replace your second for loop (for ind, sumdias in dias.iteritems()) with something like:
pd.cut(consumption.days, [-1, 180, 365, np.inf], labels=['a', 'b', 'c']).value_counts()

TypeError: bad operand type for unary -: 'str'

I've got a problem with Python 2.7.3-32bits on Windows. I put this code to see if anyone can help me out with this error. The comments are in Spanish but it don't affect the code.
import gtk
import numpy
import math
import os
#Pedimos el nombre de la imagen de origen
nombreFich = input("Por favor, introduzca el nombre de la imagen de origen:")
#Validar que existe el fichero
imagen1 = gtk.Image()
imagen1.set_from_file('C:\\Users\\xxx\\Desktop\\xxxx.png')
pb1 = imagen1.get_pixbuf()
pm1 = pb1.get_pixels_array()
#Hacemos una copia de la imagen
pm2 = pm1.copy()
#Validamos los puntos de distorsion hasta que sean validos
puntos = " "
arrayPuntos = " "
while(puntos == " " and len(arrayPuntos) < 4):
print"Por favor, introduzca los puntos de distorsión xc yc r e:"
puntos= raw_input()
arrayPuntos = puntos.split(" ")
#Sacamos los puntos separando la cadena por el caracter espacio
xc =(puntos[0])
yc =(puntos[1])
r =(puntos[2])
e =(puntos[3])
#función que calcula el grado de distorsión
def grado(self,z,e):
if(z>1):
return 1
elif(e<0):
return (1/z)**(-e/(1-e))
else:
return z**e
#Distorsionamos la imagen
def distors(xc,yc,r,e,x,y):
d = math.sqrt(x**2+y**2)#Sacamos la distancia
z = d/r
if(z!=0):
g=grado(z,e)
xm=x*g
ym=y*g
return xm,ym
else:
xm=x
ym=y
return xm,ym
def recorrido (pm1, xc, yc, r, e):
pm2 = pm1.copy()
x= str(--r)
y= str(--r)
while (y <= r):
while (x <= r):
xm, ym = mover(xc, yc, r, e, x, y)
pm2[yc+y][xc+x] = pm1[yc+ym][xc+xm]
x = x+1
y= y+1
x= -r
return pm2
pm2 = recorrido(pm1, xc, yc, r, e)
#Guardamos los cambios
pb2 = gtk.gdk.pixbuf_new_from_array(pm2,pb1.get_colorspace(),pb1.get_bits_per_sample())
nomfich2 = nombreFich+"_copia"
ext = os.path.splitext("C:\\Users\xxx\Desktop\xxxx.png_copia")[1][1:].lower()
pb2.save("C:\\Users\xxx\Desktop\xxxx.png_copia",ext)
print"FINISH"
When I run the python code I get the following error:
Traceback (most recent call last):
File "F:\Dropbox\Práctica Pitón\Práctica3.0.py", line 71, in <module>
pm2 = recorrido(pm1, xc, yc, r, e)
File "F:\Dropbox\Práctica Pitón\Práctica3.0.py", line 59, in recorrido
x= str(--r)
TypeError: bad operand type for unary -: 'str'
The error message is telling you that r is a string. You can't negate a string.
Why is it a string? Well, it seems to come from here:
# ...
puntos= raw_input()
arrayPuntos = puntos.split(" ")
# ...
r =(puntos[2])
The split method on a string returns a list of strings.
So, how do you solve this? Well, if r is, say, the string "22", then float(r) is the float 22.0, and int(r) is the integer 22. One of those is probably what you want.
Once you add, say, r=int(r), your --r will no longer be an exception.
But it probably isn't what you want. In Python, --r just means the negation of the negation of r—in other words, it's the same as -(-(r)), which is just r. You're probably looking for the equivalent of the C prefix operator--, which decrements the variable and returns the new value. There is no such operator in Python; in fact, there are no operators that modify a variable and then return the value.
This is part of a larger issue. Python is designed to make statements and expressions as distinct as possible, to avoid confusion. C is designed to make as many things as possible expressions, to save typing. So, you often can't just translate one into the other line by line.
In this case, you have to do it in two steps, as Thanasis Petsas shows:
r -= 1
x = str(r)
Increment ++ and decrement -- operators are not supported in python.
You can use instead this:
r -= 1
x = str(r)

Categories