How I can set a specific cell from excel in python? - python

I'm doing a function with python where I have to create a matrix in Excel, but for that I need to know how I can manipulate some keyboard request to specific excel cells positions in it to create this matrix with some values in this cells.
The code that I have right now it is here:
import sys
import openpyxl as opxl
def crear_menu():
menu=int(input("Elija una opción \n 1.Crear parámetros \n
2.Aplicar Dijkstra \n 3.Aplicar Kruskal \n 4.Salir"))
if menu == 1:
min_nodos()
elif menu == 2:
dijkstra()
elif menu == 3:
kruskal()
elif menu == 4:
sys.exit()
else:
print("\n ERROR: Elija una opción válida.")
crear_menu()
def crear_matriz_adyacente2(cant_nodos):
lista_nodos = []
lista_matriz = []
lista_filas = []
lista_columnas = []
libro = opxl.Workbook()
pagina = libro.active
pagina.title = "matriz_de_adyacencia"
i = 0
while(i < cant_nodos):
num = str(i+1)
nodo = str(input("Ingresar nombre del nodo " + num + ":"))
if nodo not in lista_nodos:
lista_nodos.append(nodo)
pagina.cell(row = i+2, column = 1, value = nodo)
pagina.cell(row = 1, column = i+2, value = nodo)
i += 1
elif(nodo < 0):
print("ERROR: Nodo no valido")
else:
print("Error: Nodo existente. \n Ingrese otro nombre: ")
libro.save("matriz_de_adyacencia.xlsx")
def min_nodos():
cant_nodos = int(input("Elija la cantidad de nodos a utilizar
(mínimo 6):"))
while(cant_nodos < 6):
print("ERROR: Elija mínimo 6 nodos y que sea entero positivo.")
cant_nodos = int(input("Elija la cantidad de nodos a utilizar (mínimo 6):"))
else:
crear_matriz_adyacente(cant_nodos)
Here in the red box I'm trying to do the matrix, but I don't know the best way to import a specific excel cell. I mean, I don't know if with this I'm referring to A2.
Thank you for your help.

Related

Delete features with PyQGIS in a loop

I have been for months trying unsuccesfully to make a function which can compare a feature with the other ones in a shp layer and if some conditions fulfill, the feature in the loop is deleted. I need it for my final work. The conditions to delete a feature have to be two: if the feature overlay the other one and if it is older than the feature that is in the loop.
def superpuestos2(capa, fecha, geom, id):
listaborrar = []
fecha_feat = fecha
fechainf_feat = datetime.strptime(fecha_feat, "%d/%m/%Y")
feat_geom = geom
features = capa.getFeatures()
for f in features:
id_feat = f.attribute('id')
if id != id_feat:
fecha_f = f.attribute('fecha')
fechainf_f = datetime.strptime(fecha_f, "%d/%m/%Y")
f_geom = f.geometry()
inters = f_geom.intersection(feat_geom)
areageom = feat_geom.area()
interarea = inters.area()
fraccion = interarea/areageom
if fraccion > 0.3:
if fechainf_feat >= fechainf_f:#si la fecha es mas antigua:
print("intersecta")#en vez de print que borre el feature de f.
listaborrar.append(f.id())
print(listaborrar)
capa.dataProvider().deleteFeatures(listaborrar)

Make a filter using a column from df in another df in python

I'm using this dataframe:
# importando o dataframe
url = 'https://raw.githubusercontent.com/ipauchner/DNC/main/kc_house_data.csv'
df = pd.read_csv(url)
After some analysis I managed to separate 25 lines from this df, the analyzes were as follows:
# encontrando os id's repetidos, ou seja, as casas que foram vendidas mais de 1 vez
id_repetido = pd.concat(g for x, g in df.groupby('id') if len(g) > 1)
id_repetido
# encontrando a primeira venda
venda2 = id_repetido.duplicated(subset=['id'], keep = 'first')
venda1 = id_repetido[~venda2]
venda1 = venda1[venda1.id != 795000620]
venda1
venda2 = id_repetido[venda2]
venda2 = venda2[venda2.id != 795000620]
venda2
venda1['id'].value_counts().sort_values()
venda2['id'].value_counts().sort_values()
lucro_prej = pd.merge_asof(venda1, venda2, on='id') # juntando as informações das vendas
lucro_prej = lucro_prej.loc[:,['id', 'price_x', 'price_y']] # unindo pelo id
lucro_prej = lucro_prej.rename({'price_x': 'primeira_venda'}, axis = 1) # renomeando a coluna
lucro_prej = lucro_prej.rename({'price_y': 'segunda_venda'}, axis = 1) # renomeando a coluna
lucro_prej
lucro_prej['lucro/prejuízo'] = lucro_prej['segunda_venda'] -
lucro_prej['primeira_venda'] # calculando o valor do lucro ou prejuízo
lucro_prej['variação'] = ((lucro_prej['segunda_venda'] - lucro_prej['primeira_venda']) /
lucro_prej['primeira_venda'] * 100).round(decimals = 2) # calculando a % do lucro ou prejuízo
lucro_prej.sort_values(by=['variação'], ascending=False, inplace = True) # ordenando em ordem crescente
lucro_prej
maiores_lucros = lucro_prej.head(25)
maiores_lucros
This generated another df (maiores_lucros) with 25 lines.
What I did was multiple filters on the df originalla(df). For example: bathrooms >=1 and <=3, bedrooms >= 2 and <=4. I got this part with the following code:
lista_casas = df[((df.bedrooms > 2) & (df.bedrooms < 6)) & (df.bathrooms >= 1) & (df.bathrooms <= 3)]
But what I needed was to make a filter so that the id's of the df maiores_lucros do not appear in the lista_casas. I even tried the following way:
id_filtrar = maiores_lucros['id'].tolist()
id_filtrar
lista_casas2 = df[df.id != id_n_filtrar]
lista_casas2
But it returns the following error:
ValueError: ('Lengths must match to compare', (21528,), (25,))
Is there any way to make this filter?

TypeError: can only concatenate tuple (not "int") to tuple - no sum()

I got this error TypeError: can only concatenate tuple (not "int") to tuple for the part of my code which is in bold. How can I do a sum without the function sum() ?
q_0_seq = ()
q_3_seq = ()
q_3 = 0
q_0 = (input('Voulez-vous ajouter un jour ? (o/n)'))
if q_0 == "o":
q_0 = True
q_0_seq = q_0_seq + (q_0,)
else:
q_0 = False
while q_0 == True:
q_3 = int(input("Combien de minutes d'activité physique avez-vous effectué?"))
q_3_seq = q_3_seq + (q_3,)
q_0 = (input('Voulez-vous ajouter un jour ? (o/n)'))
q_3_sum = 0
for q_3 in q_3_seq:
**q_3_sum = q_3_seq + q_3**
q_3_mean = q_3_sum / len(q_3_seq)
if q_3_mean < 30:
print("Vous ne faites pas suffisamment de sport! Visez 30 minutes par jour en moyenne.")```
Make that:
q_3_sum = q_3_sum + q_3

How can i show index on the input of user?

I can show for user the number of task, example: input('Start task 1:' )
n = input('Digite o numero de trabalhos: ')
i = 0
job = []
while(i != n):
start_job1 = int(input('Inicio da tarefa: ' ))
final_job1 = int(input('Final da tarefa: '))
lucro_job1 = int(input('Valor da tarefa: '))
job.append(Job(start_job1, final_job1, lucro_job1))
i = i+1
print("Melhor lucro sera: "),
print schedule(job)
You can format your string with the str.format method:
start_job1 = int(input('Inicio da tarefa {}: '.format(i + 1)))
or with the string formatting operator:
start_job1 = int(input('Inicio da tarefa %d: ' % (i + 1)))

run sage worksheet as a script?

Hi I have written a code in sageworksheet format, it runs nice and smooth on sagecloud, but I have one problem : I want to make it more interactive so the user can enter the parameters by himself, so I'm willing to convert this into a sage script or a pyhton script, I have installed sage on my ubuntu machine, again the code runs on the notebook but not on the console it gives me some syntax error on " P.x " (the same goes if I try to run it as a python script) All I want is to make it run as a Python script or Sage script so I can use input function to ask users to enter the parameters ! Here is the code :
P.<x> = PolynomialRing(ZZ);
def bezout(f,g):
P.<x> = PolynomialRing(QQ)
f = f+x-x
g = g+x-x
e=xgcd(f,g)
gcd=e[0]
u=e[1]
v=e[2]
return (u,v,gcd)
def polymod(f,q):
P.<x> = PolynomialRing(QQ)
f = f
c = f.coefficients(sparse=False)
N = len(c)
for i in range(N):
c[i] = Rational(c[i]).mod_ui(q);
p = sum(c[i]*(x^(i)) for i in range(N));
return p
def center(f,q):
u = q/2
v = -u
c = f.coefficients(sparse=False)
N = len(c)
for i in range(N):
if c[i]<v:
c[i] = c[i] + q;
elif c[i]>u:
c[i] = c[i] - q;
else:
c[i] = c[i];
p = sum(c[i]*(x^(i)) for i in range(N));
return p
class Ntru:
N = None
p = None
q = None
d = None
f = None
g = None
h = None
fp = None
fq = None
Phi = None
def __init__(self,N,p,q,d):
self.N = N
self.p = p
self.q = q
self.d = d
v = self.N
self.Phi = x^v -1
def test(self):
if not is_prime(self.N):
print "N n est pas premier, pensez a changer ce parametre"
return False
if gcd(self.N,self.p) != 1:
print "N et p ne sont pas premiers entre eux, pensez a changer ces parametres"
return False
if gcd(self.N,self.q) != 1:
print "N et q ne sont pas premiers entre eux, pensez a changer ces parameres"
return False
if self.q <= (6*self.d+1)*self.p :
print "q doit etre superieur a (6d+1)*p "
return False
return True
def genPublicKey(self,f_new,g_new):
self.f = f_new
self.g = g_new
(b_f,b_phi,bz) = bezout(self.f,self.Phi)
self.fp = polymod(b_f,self.p)
self.fq = polymod(b_f,self.q)
self.h = polymod((self.fq*self.g).quo_rem(self.Phi)[1],self.q)
if not self.test():
print "le cryptage ne peut s effectuer avec ces parametres !"
quit()
def encrypt(self,message,rand):
if self.h!=None:
temp=(self.p*rand*self.h + message).quo_rem(self.Phi)[1]
e=polymod(temp,self.q)
return e
else:
print "Impossible de faire le cryptage : la cle n a pas encore ete generee"
print "Veuillez en generer une avec la fonction genPublicKey"
def decrypt(self,encryptedMsg):
a = (self.f*encryptedMsg).quo_rem(self.Phi)[1]
a = polymod(a,self.q)
a = center(a,self.q)
tmp = (self.fp*a).quo_rem(self.Phi)[1]
m=polymod(tmp,self.p)
return m
NTRU=Ntru(167,3,128,3)
f = 1+x-x^2-x^3-x^4+x^5+x^6
g = -1+x^2+x^3+x^4-x^5-x^6
NTRU.f = f
NTRU.g = g
NTRU.genPublicKey(f,g)
print "La cle publique est : ",NTRU.h
msg = 1+x+x^4+x^5+x^6
rand = -1 -x + x^2 + x^3 - x^4 + x^6
enc = NTRU.encrypt(msg,rand)
print "Le Message crypte est : ",enc
dec = NTRU.decrypt(enc)
print "Le Message dechiffre est : ",dec
print "Le Message en clair etait : ",msg
Thank you !
For a python script, you can start by taking your code at the bottom and defining a function as a main entry point like:
def main():
NTRU=Ntru(167,3,128,3)
f = 1+x-x^2-x^3-x^4+x^5+x^6
g = -1+x^2+x^3+x^4-x^5-x^6
NTRU.f = f
NTRU.g = g
NTRU.genPublicKey(f,g)
print "La cle publique est : ",NTRU.h
msg = 1+x+x^4+x^5+x^6
rand = -1 -x + x^2 + x^3 - x^4 + x^6
enc = NTRU.encrypt(msg,rand)
print "Le Message crypte est : ",enc
dec = NTRU.decrypt(enc)
print "Le Message dechiffre est : ",dec
print "Le Message en clair etait : ",msg
Then after this code block, you need to tell python what code you want it to run as if it was a script like so:
if __name__ == "__main__":
main()
If you would like to run it as an executable from the ubuntu command line, I would suggest adding a shebang at the top like:
#!/bin/python //this should be the path to your python executable
If you are interested in adding command line arguments to the script for user input, I suggest looking into the argParse library included with python:
https://docs.python.org/3.3/library/argparse.html for python 3
https://docs.python.org/2/library/argparse.html for python 2.7
Unfortunately I am unfamiliar with Sage; I hope this gets you started in the right direction.

Categories