Related
Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 4 days ago.
Improve this question
Estou tendo problemas com meu código ele me retorna sempre o mesmo erro sendo ele:
Traceback (most recent call last):
File "c:\codgos\IA\AAHAS.py", line 77, in <module>
caminho, distancia_percorrida = a_estrela(estacaoini, estacaofinal)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\codgos\IA\AAHAS.py", line 70, in a_estrela
nova_estimativa_custo = distancia_em_linha_reta(vizinho, destino)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\codgos\IA\AAHAS.py", line 39, in distancia_em_linha_reta
return distancias[origem][destino]
~~~~~~~~~~~~~~~~~~^^^^^^^^^
KeyError: 'N'
No inicio achei que poderia ser algo com como as distancias estão escritas em Caps, mas alteralas não mudou nada
Esse é o código atual:
# Definindo a tabela de distâncias entre as estações
distancias = {
'A' : {'B':11,'C':20,'D':27,'E':40,'F':43,'G':39,'H':28,'I':18,'J':10,'K':18,'L':30,'M':30,'N':32},
'B' : {'A':11,'C':9,'D':16,'E':29,'F':32,'G':28,'H':19,'I':11,'J':4,'K':17,'L':23,'M':21,'N':24},
'C' : {'A':20,'B':9,'D':7,'E':20,'F':22,'G':19,'H':15,'I':10,'J':11,'K':21,'L':21,'M':13,'N':18},
'D' : {'A':27,'B':16,'C':7,'E':13,'F':16,'G':12,'H':13,'I':13,'J':18,'K':26,'L':21,'M':11,'N':17},
'E' : {'A':40,'B':29,'C':20,'D':13,'F':3,'G':2,'H':21,'I':25,'J':31,'K':38,'L':27,'M':16,'N':20},
'F' : {'A':43,'B':32,'C':22,'D':16,'E':3,'G':4,'H':23,'I':28,'J':33,'K':41,'L':30,'M':17,'N':20},
'G' : {'A':39,'B':28,'C':19,'D':12,'E':2,'F':4,'H':22,'I':25,'J':29,'K':38,'L':28,'M':13,'N':17},
'H' : {'A':28,'B':19,'C':15,'D':13,'E':21,'F':23,'G':22,'I':9,'J':22,'K':18,'L':7,'M':25,'N':30},
'I' : {'A':18,'B':11,'C':10,'D':13,'E':25,'F':28,'G':25,'H':9,'J':13,'K':12,'L':12,'M':23,'N':28},
'J' : {'A':10,'B':4,'C':11,'D':18,'E':31,'F':33,'G':29,'H':22,'I':13,'K':20,'L':27,'M':20,'N':23},
'K' : {'A':18,'B':17,'C':21,'D':26,'E':38,'F':41,'G':38,'H':18,'I':12,'J':20,'L':15,'M':35,'N':39},
'L' : {'A':30,'B':23,'C':21,'D':21,'E':27,'F':30,'G':28,'H':7,'I':12,'J':27,'K':15,'M':31,'N':37},
'M' : {'A':30,'B':21,'C':13,'D':11,'E':16,'F':17,'G':13,'H':25,'I':23,'J':20,'K':35,'L':31,'N':5},
'N' : {'A':32,'B':24,'C':18,'D':17,'E':20,'F':20,'G':17,'H':30,'I':28,'J':23,'K':39,'L':37,'M':5}
}
# Definindo as conexões entre as estaçõesA
conexoes = {
'A': ['B'],
'B': ['A', 'J', 'I', 'C'],
'C' : ['B', 'D', 'I', 'N'],
'D' : ['C', 'H', 'E', 'M'],
'E' : ['D', 'F', 'G', 'H'],
'F' : ['E'],
'G' : ['E'],
'H' : ['D', 'E', 'I', 'L'],
'I' : ['B', 'C', 'K', 'H'],
'J' : ['B'],
'K' :['I'],
'L' :['H'],
'M' :['C','D', 'N'],
'N' :['M']
}
# Definindo a função heurística (distância em linha reta até o destino)
def distancia_em_linha_reta(origem, destino):
return distancias[origem][destino]
# Definindo a função de avaliação
def custo_total(caminho):
distancia_total = 0
tempo_total = 0
for i in range(len(caminho) - 1):
distancia_total += distancias[caminho[i]][caminho[i+1]]
if i > 0 and caminho[i] not in conexoes[caminho[i-1]]:
tempo_total += 4
tempo_total += distancia_total / 30
return distancia_total + tempo_total
# Implementando o algoritmo A*
def a_estrela(origem, destino):
fronteira = [(origem, [origem], 0, distancia_em_linha_reta(origem, destino))]
visitados = set()
while fronteira:
fronteira.sort(key=lambda x: x[2] + x[3])
proximo = fronteira.pop(0)
estacao = proximo[0]
caminho = proximo[1]
distancia_percorrida = proximo[2]
estimativa_custo = proximo[3]
if estacao == destino:
return caminho, distancia_percorrida
visitados.add(estacao)
for vizinho in conexoes[estacao]:
if vizinho not in visitados:
novo_caminho = caminho + [vizinho]
nova_distancia = distancia_percorrida + distancias[estacao][vizinho]
nova_estimativa_custo = distancia_em_linha_reta(vizinho, destino)
fronteira.append((vizinho, novo_caminho, nova_distancia, custo_total(novo_caminho) + nova_estimativa_custo))
return None
# Testando a função com os dados de exemplo
estacaoini = input("Qual sua estação de origem(A, B, C, D, E, F, G, H, I, J, K, L, M ou N):")
estacaofinal = input("Qual sua estação de destino(A, B, C, D, E, F, G, H, I, J, K, L, M ou N):")
caminho, distancia_percorrida = a_estrela(estacaoini, estacaofinal)
print('Melhor caminho:', caminho)
print('Distância percorrida:', distancia_percorrida)
Estou tentando descobrir qual seria o problema mas não consigo de maneira nenhuma, já vasculhei, até a famosa ia do momento não conseguiu me ajudar
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()```
I'm trying to code tdma. I have a working program for most of the process, but I can't get the results asked.
I'm supposed to get [2,3,-1,4,-2] as a result, but I get : [-0.5120543981481481, -0.1787210648148148, 0.4824421296296296, 0.4879012345679012, -3.7802469135802474].
I've checked one by one the coefficients for each step, and they're good. I think the problem comes from resolve2, but it worked for gauss pivot. It still can be math, but I'm pretty sure it's not.
import numpy as np
A=np.array([[3.,-3.,0,0,0],[2.,8.,4.,0,0],[0,4.,-8.,3.,0],[0,0,-7.,5.,1.],[0,0,0,-1.,3.]])
B0=[-3.,3.,25.,13.,-10.]
B = np.array([B0]).reshape(len(B0),1)
def det(A):
return np.linalg.det(A)
def op_linescal(A,i,x):
n = len(A[0]) # nbre de colonnes de A
for k in range(n):
A[i,k] = x*A[i,k] # la ligne Li devient la ligne x*Li
return A #retourne la nouvelle matrice
def op_linecombi(A,i,j,x):
n = len(A[0]) # nbre de colonnes de A
for k in range(n):
A[i,k] = A[i,k] + x*A[j,k] # la ligne Li devient la ligne Li + x*Lj
return A #retourne la nouvelle matrice
def tdma1(a,b):
ne = A.shape[0] #donne le nombre d'équations donc de ligne
if ne < 3:
return print("On ne peut pas résoudre avec l'algorithme de Thomas")
if det(A) == 0: # vérifie condition pour appliquer Thomas (matrice inversible : det(A) != 0)
return print("On ne peut pas utiliser cet algorithme de Thomas, la matrice A est singulière.")
l = A.copy() #création de la matrice à modifier
b = B.copy()
for i in range(ne):
# print("{}\n{}".format(a,b))
if i == 0 :
x = 1/l[i,i]
op_linescal(l,i,x) # on divise L1 par b1
op_linescal(b,i,x) # reproduction en b
elif i != 0 and i < ne-1: # i = 1,...,N-1
x1 = -l[i,i-1]
op_linecombi(l,i,i-1,x1) # Li => Li - ai*Li-1
op_linecombi(b,i,i-1,x1)
x2 = 1/l[i,i] # où a[i,i] = bi - ai*ci-1
op_linescal(l,i,x2) # Li => Li / (bi')
op_linescal(b,i,x2)
else: # i = N
x1 = -l[i,i-1]
op_linecombi(l,i,i-1,x1) # Li => Li - ai*Li-1
op_linecombi(b,i,i-1,x1)
print('\n',np.round(a,3))
print('\n{}\n'.format(np.round(b,2)))
return a,b
def resolve2(a,b):
"Renvoie la solution du système Ax = b lorsque A est triangulaire supérieure inversible"
n =len(a[0])
x = [0 for i in range(n)]
x[n-1] = b[n-1,0]/a[n-1,n-1]
for i in range(n-2,-1,-1):
s = 0
for j in range(i+1, n):
s = s + a[i,j]*x[j]
x[i] = (b[i,0] - s)/ a[i,i]
return x
def thomas(a, b):
if det(a) == 0: # vérifie condition pour appliquer Gauss
return print("On ne peut pas utiliser Gauss, la matrice A n'est pas inversible.")
a1,b1 = tdma1(a, b)
x = resolve2(a1, b1)
return x
print(thomas(A, B))
I've got the following code:
from itemspecs import itemspecs
x = itemspecs.split('###')
res = []
for item in x:
res.append(item.split('##'))
print(res)
This imports a string from another document. And gives me the following:
[['\n1\nWie was de Nederlandse scheepvaarder die de Spaanse zilvervloot veroverde?\n',
'\nA. Michiel de Ruyter\nB. Piet Heijn\nC. De zilvervloot is nooit door de Nederlanders
onderschept\n', '\nB\n', '\nAntwoord B De Nederlandse vlootvoogd werd hierdoor bekend.\n'],
['\n2\nIn welk land ligt Upernavik?\n', '\nA. Antartica\nB. Canada\nC. Rusland\nD.
Groenland\nE. Amerika\n', '\nD\n', '\nAntwoord D Het is een dorp in Groenland met 1224
inwoners.\n']]
But now I want to remove all the \n from every end and beginning of every element in this list. How can I do this?
You can do that by stripping "\n" as follow
a = "\nhello\n"
stripped_a = a.strip("\n")
so, what you need to do is iterate through the list and then apply the strip on the string as shown below
res_1=[]
for i in res:
tmp=[]
for j in i:
tmp.append(j.strip("\n"))
res_1.append(tmp)
The above answer just removes \n from start and end. if you want to remove all the new lines in a string, just use .replace('\n"," ") as shown below
res_1=[]
for i in res:
tmp=[]
for j in i:
tmp.append(j.replace("\n"))
res_1.append(tmp)
strip() is easiest method in this case, but if you want to do any advanced text processing in the future, it isn't bad idea to learn regular expressions:
import re
from pprint import pprint
l = [['\n1\nWie was de Nederlandse scheepvaarder die de Spaanse zilvervloot veroverde?\n',
'\nA. Michiel de Ruyter\nB. Piet Heijn\nC. De zilvervloot is nooit door de Nederlandersonderschept\n',
'\nB\n',
'\nAntwoord B De Nederlandse vlootvoogd werd hierdoor bekend.\n'],
['\n2\nIn welk land ligt Upernavik?\n',
'\nA. Antartica\nB. Canada\nC. Rusland\nD.Groenland\nE. Amerika\n',
'\nD\n', '\nAntwoord D Het is een dorp in Groenland met 1224inwoners.\n']]
l = [[re.sub(r'^([\s]*)|([\s]*)$', '', j)] for i in l for j in i]
pprint(l, width=120)
Output:
[['1\nWie was de Nederlandse scheepvaarder die de Spaanse zilvervloot veroverde?'],
['A. Michiel de Ruyter\nB. Piet Heijn\nC. De zilvervloot is nooit door de Nederlandersonderschept'],
['B'],
['Antwoord B De Nederlandse vlootvoogd werd hierdoor bekend.'],
['2\nIn welk land ligt Upernavik?'],
['A. Antartica\nB. Canada\nC. Rusland\nD.Groenland\nE. Amerika'],
['D'],
['Antwoord D Het is een dorp in Groenland met 1224inwoners.']]
l have two columns that represent : right sequence and predicted sequence. l want to make statistics on the number of deletion, substitution and insertion by comparing each right sequence with its predicted sequence.
l did the levenstein distance to get the number of characters which are different (see the function below) and error_dist function to get the most common errors (in terms of substitution) :
here is a sample of my data :
de de
date date
pour pour
etoblissemenls etablissements
avec avec
code code
communications communications
r r
seiche seiche
titre titre
publiques publiques
ht ht
bain bain
du du
ets ets
premier premier
dans dans
snupape soupape
minimum minimum
blanc blanc
fr fr
nos nos
au au
bl bl
consommations consommations
somme somme
euro euro
votre votre
offre offre
forestier forestier
cs cs
de de
pour pour
de de
paye r
cette cette
votre votre
valeurs valeurs
des des
gfda gfda
tva tva
pouvoirs pouvoirs
de de
revenus revenus
offre offre
ht ht
card card
noe noe
montant montant
r r
comprises comprises
quantite quantite
nature nature
ticket ticket
ou ou
rapide rapide
de de
sous sous
identification identification
du du
document document
suicide suicide
bretagne bretagne
tribunal tribunal
services services
cif cif
moyen moyen
gaec gaec
total total
lorsque lorsque
contact contact
fermeture fermeture
la la
route route
tva tva
ia ia
noyal noyal
brie brie
de de
nanterre nanterre
charcutier charcutier
semestre semestre
de de
rue rue
le le
bancaire bancaire
martigne martigne
recouvrement recouvrement
la la
sainteny sainteny
de de
franc franc
rm rm
vro vro
here is my code
import pandas as pd
import collections
import numpy as np
import matplotlib.pyplot as plt
import distance
def error_dist():
df = pd.read_csv('data.csv', sep=',')
df = df.astype(str)
df = df.replace(['é', 'è', 'È', 'É'], 'e', regex=True)
df = df.replace(['à', 'â', 'Â'], 'a', regex=True)
dictionnary = []
for i in range(len(df)):
if df.manual_raw_value[i] != df.raw_value[i]:
text = df.manual_raw_value[i]
text2 = df.raw_value[i]
x = len(df.manual_raw_value[i])
y = len(df.raw_value[i])
z = min(x, y)
for t in range(z):
if text[t] != text2[t]:
d = (text[t], text2[t])
dictionnary.append(d)
#print(dictionnary)
dictionnary_new = dict(collections.Counter(dictionnary).most_common(25))
pos = np.arange(len(dictionnary_new.keys()))
width = 1.0
ax = plt.axes()
ax.set_xticks(pos + (width / 2))
ax.set_xticklabels(dictionnary_new.keys())
plt.bar(range(len(dictionnary_new)), dictionnary_new.values(), width, color='g')
plt.show()
enter image description here
and the levenstein distance :
def levenstein_dist():
df = pd.read_csv('data.csv', sep=',')
df=df.astype(str)
df['string diff'] = df.apply(lambda x: distance.levenshtein(x['raw_value'], x['manual_raw_value']), axis=1)
plt.hist(df['string diff'])
plt.show()
enter image description here
Now l want to make a histograms showing three bins : number of substitution, number of insertion and number of deletion . How can l proceed ?
Thank you
Thanks to the suggestions of #YohanesGultom the answer for the problem can be found here :
http://www.nltk.org/_modules/nltk/metrics/distance.html
or
https://gist.github.com/kylebgorman/1081951