I don't managed to make leastsq run with
The programme etude is run 5 times but there is no change of the parameters p[0] and p[1].
I launch the etude file witch produce a file of data witch I read by the Read_And_Save_Value fonction. The data print depend on the p[0] p[&] paramaters.
The template is launch by Lancer_Etude it remplace the etude file by the etude.template with the caractère $A and $B are remplaced by their actual value.
def Read_And_Save_Value(p,x):
fichier = open( "sechage_granger.dat", "r") # ouverture en lecture
txt = fichier.read()
fichier.close()
b1 = zeros(23)
b2 = zeros(23)
for i in range(6, 29):
print 'i', i
line = txt.split("\n")[i] # iere ligne de donnees
line = line.split(" ") # le separateur utilise a l'ecriture
b1[i-6] = float(line[1])
b2[i-6] = float(line[3])
print 'b1', b1
print 'b2', b2
c= [0,24, 46, 143, 166, 190, 388, 646, 843, 1011, 2015,
2853, 3554, 4514, 5187, 6046, 6525, 7222,
7923, 8877, 10415, 11068, 12317, 13251, 14757, 15843,
17447, 18459, 19874, 22325, 24216,
27071, 33651, 39987, 103995, 108660,109000]
def f_int(p,x):
return UnivariateSpline(b1, b2, s=2)(x)
#x = s(c)
plt.plot(b1, b2, '.-')
#plt.plot(c, x)
plt.show()
return f_int(p,x)
def Lancer_Etude(p,x,C0,Ceq):
file_in = open('etude.template', 'r')
file_out = open('etude', 'w')
dico = dict(A=p[0], B=p[1],C0=C0, Ceq=Ceq)
for line_0 in file_in.readlines():
line_1 = Template(line_0).substitute(dico)
file_out.write(line_1)
file_in.close()
file_out.close()
os.system('bash ./launch_study.sh')
return Read_And_Save_Value(p,x)
# Define the error
def residuals(p,x, y):
fichier.write(str(p[0])+";"+str(p[1])+"\n") # ecriture d'une ligne de donnees (choix arbitraire du format)
print 'x'*80
print 'fin etude'
#print 'fres', fres
print 'y', y
err = y - Lancer_Etude(p,x,150.,50.)
fichier.write('erreur -> ')
fichier.write(str(sum(np.multiply(err, err)))+"\n")
# print 'err', err
return err
Related
I'm trying to read a json that I created in the script myself. When I try to access one of his "attributes" after reading the following error appears:
Traceback (most recent call last):
File "index.py", line 74, in <module>
print(json_leitura['items'])
TypeError: string indices must be integers
the same error occurs when I put it print(json_leitura['topico']) at the end.
I don't know if the creation of the JSON file is correct. I don't know if the reading is correct. When I try to trigger the "print" command or assign the value to a variable. The error described above always occurs.
Code
import requests
import json
def requisicao_api(url):
resposta = requests.get(url)
if resposta.status_code == 200:
return resposta.json()
else:
return resposta.status_code
def requisicao_url(url):
dados_api = requisicao_api(url)
return dados_api
def monta_lista_repos_topico(topico):
lista_registros = []
# Percorre os 1000 primeiros registros, ou seja, 10 páginas de 100 registros.
for x in range(1,2):
urlprincipal = f'https://api.github.com/search/repositories?q=topic:{str(topico)}&sort=stars&order=desc&page={str(x)}&per_page=1'
print(urlprincipal)
dados_api = requisicao_url(urlprincipal)
if type(dados_api) is int: # Caso ocorra algum erro. Sai do loop e retorna lista vazia
print("Erro: " + str(dados_api))
break
else:
#Pega os repositórios no item e insere em uma lista
print("Página: " + str(x))
print(dados_api['items'])
items = dados_api['items']
for i in range(len(items)):
lista_registros.append(items[i])
return(lista_registros)
def gravar_arquivo_json(nome_arquivo, dados):
with open(nome_arquivo, 'w', encoding='utf-8') as f:
json.dump(dados, f, ensure_ascii=False, indent=2, sort_keys=False, separators=(',' , ':'))
def ler_arquivo_json(nome_arquivo):
with open(nome_arquivo, 'r', encoding='utf8') as f:
return json.load(f)
#================================================================================#
# MAIN #
#================================================================================#
# Alterar essas duas variáveis
topico = "open-data"
nome_arquivo = "open-data.json"
# Monta uma lista com os repositórios do tópico
lista_repos = monta_lista_repos_topico(topico)
# Monta um json com tópico e lista de repositórios
registro_json = {}
registro_json['topico'] = topico
registro_json['items'] = lista_repos
arquivo_json = json.dumps(registro_json, indent=2, sort_keys=False)
print(arquivo_json)
# Grava json
gravar_arquivo_json(nome_arquivo, arquivo_json)
# Leitura json
json_leitura = ler_arquivo_json(nome_arquivo)
print(json_leitura['items'])
JSON
"{\n \"topico\": \"open-data\",\n \"items\": [\n {\n \"id\": 62087567,\n \"node_id\": \"MDEwOlJlcG9zaXRvcnk2MjA4NzU2Nw==\",\n \"name\": \"serenata-de-amor\",\n \"full_name\": \"okfn-brasil/serenata-de-amor\",\n \"private\": false,\n \"owner\": {\n \"login\": \"okfn-brasil\",\n \"id\": 1666382,\n \"node_id\": \"MDEyOk9yZ2FuaXphdGlvbjE2NjYzODI=\",\n \"avatar_url\": \"https://avatars.githubusercontent.com/u/1666382?v=4\",\n \"gravatar_id\": \"\",\n \"url\": \"https://api.github.com/users/okfn-brasil\",\n \"html_url\": \"https://github.com/okfn-brasil\",\n \"followers_url\": \"https://api.github.com/users/okfn-brasil/followers\",\n \"following_url\": \"https://api.github.com/users/okfn-brasil/following{/other_user}\",\n \"gists_url\": \"https://api.github.com/users/okfn-brasil/gists{/gist_id}\",\n \"starred_url\": \"https://api.github.com/users/okfn-brasil/starred{/owner}{/repo}\",\n \"subscriptions_url\": \"https://api.github.com/users/okfn-brasil/subscriptions\",\n \"organizations_url\": \"https://api.github.com/users/okfn-brasil/orgs\",\n \"repos_url\": \"https://api.github.com/users/okfn-brasil/repos\",\n \"events_url\": \"https://api.github.com/users/okfn-brasil/events{/privacy}\",\n \"received_events_url\": \"https://api.github.com/users/okfn-brasil/received_events\",\n \"type\": \"Organization\",\n \"site_admin\": false\n },\n \"html_url\": \"https://github.com/okfn-brasil/serenata-de-amor\",\n \"description\": \"\\ud83d\\udd75 Artificial Intelligence for social control of public administration\",\n \"fork\": false,\n \"url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor\",\n \"forks_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/forks\",\n \"keys_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/keys{/key_id}\",\n \"collaborators_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/collaborators{/collaborator}\",\n \"teams_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/teams\",\n \"hooks_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/hooks\",\n \"issue_events_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/issues/events{/number}\",\n \"events_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/events\",\n \"assignees_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/assignees{/user}\",\n \"branches_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/branches{/branch}\",\n \"tags_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/tags\",\n \"blobs_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/git/blobs{/sha}\",\n \"git_tags_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/git/tags{/sha}\",\n \"git_refs_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/git/refs{/sha}\",\n \"trees_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/git/trees{/sha}\",\n \"statuses_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/statuses/{sha}\",\n \"languages_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/languages\",\n \"stargazers_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/stargazers\",\n \"contributors_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/contributors\",\n \"subscribers_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/subscribers\",\n \"subscription_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/subscription\",\n \"commits_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/commits{/sha}\",\n \"git_commits_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/git/commits{/sha}\",\n \"comments_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/comments{/number}\",\n \"issue_comment_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/issues/comments{/number}\",\n \"contents_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/contents/{+path}\",\n \"compare_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/compare/{base}...{head}\",\n \"merges_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/merges\",\n \"archive_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/{archive_format}{/ref}\",\n \"downloads_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/downloads\",\n \"issues_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/issues{/number}\",\n \"pulls_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/pulls{/number}\",\n \"milestones_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/milestones{/number}\",\n \"notifications_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/notifications{?since,all,participating}\",\n \"labels_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/labels{/name}\",\n \"releases_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/releases{/id}\",\n \"deployments_url\": \"https://api.github.com/repos/okfn-brasil/serenata-de-amor/deployments\",\n \"created_at\": \"2016-06-27T20:55:11Z\",\n \"updated_at\": \"2021-06-03T02:10:38Z\",\n \"pushed_at\": \"2021-06-01T17:54:22Z\",\n \"git_url\": \"git://github.com/okfn-brasil/serenata-de-amor.git\",\n \"ssh_url\": \"git#github.com:okfn-brasil/serenata-de-amor.git\",\n \"clone_url\": \"https://github.com/okfn-brasil/serenata-de-amor.git\",\n \"svn_url\": \"https://github.com/okfn-brasil/serenata-de-amor\",\n \"homepage\": \"https://serenata.ai/en\",\n \"size\": 71008,\n \"stargazers_count\": 4283,\n \"watchers_count\": 4283,\n \"language\": \"Python\",\n \"has_issues\": true,\n \"has_projects\": false,\n \"has_downloads\": true,\n \"has_wiki\": false,\n \"has_pages\": false,\n \"forks_count\": 696,\n \"mirror_url\": null,\n \"archived\": false,\n \"disabled\": false,\n \"open_issues_count\": 66,\n \"license\": {\n \"key\": \"mit\",\n \"name\": \"MIT License\",\n \"spdx_id\": \"MIT\",\n \"url\": \"https://api.github.com/licenses/mit\",\n \"node_id\": \"MDc6TGljZW5zZTEz\"\n },\n \"forks\": 696,\n \"open_issues\": 66,\n \"watchers\": 4283,\n \"default_branch\": \"main\",\n \"score\": 1.0\n }\n ]\n}"
The problem is in the line
arquivo_json = json.dumps(registro_json, indent=2, sort_keys=False)
Which according to the documentation, json.dumps "Serializes obj to a JSON formatted str according to conversion table"
In effect, the problem is that you are serializing the registro_json object twice, and ending up with a str. If you remove the offending line and directly pass registro_json to the gravar_arquivo_json function, everything should work.
Updated code:
import requests
import json
def requisicao_api(url):
resposta = requests.get(url)
if resposta.status_code == 200:
return resposta.json()
else:
return resposta.status_code
def requisicao_url(url):
dados_api = requisicao_api(url)
return dados_api
def monta_lista_repos_topico(topico):
lista_registros = []
# Percorre os 1000 primeiros registros, ou seja, 10 páginas de 100 registros.
for x in range(1,2):
urlprincipal = f'https://api.github.com/search/repositories?q=topic:{str(topico)}&sort=stars&order=desc&page={str(x)}&per_page=1'
print(urlprincipal)
dados_api = requisicao_url(urlprincipal)
if type(dados_api) is int: # Caso ocorra algum erro. Sai do loop e retorna lista vazia
print("Erro: " + str(dados_api))
break
else:
#Pega os repositórios no item e insere em uma lista
print("Página: " + str(x))
print(dados_api['items'])
items = dados_api['items']
for i in range(len(items)):
lista_registros.append(items[i])
return(lista_registros)
def gravar_arquivo_json(nome_arquivo, dados):
with open(nome_arquivo, 'w', encoding='utf-8') as f:
json.dump(dados, f, ensure_ascii=False, indent=2, sort_keys=False, separators=(',' , ':'))
def ler_arquivo_json(nome_arquivo):
with open(nome_arquivo, 'r', encoding='utf8') as f:
return json.load(f)
#================================================================================#
# MAIN #
#================================================================================#
# Alterar essas duas variáveis
topico = "open-data"
nome_arquivo = "open-data.json"
# Monta uma lista com os repositórios do tópico
lista_repos = monta_lista_repos_topico(topico)
# Monta um json com tópico e lista de repositórios
registro_json = {}
registro_json['topico'] = topico
registro_json['items'] = lista_repos
# Grava json
gravar_arquivo_json(nome_arquivo, registro_json)
# Leitura json
json_leitura = ler_arquivo_json(nome_arquivo)
print(json_leitura['items'])
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
I have a problem with my code (trying to make the NIM game with a Tkinter GUI). Anyhow i cant get my functions (Munt1, Munt2) to subtract to my global (aantal_munten). And i dont know how to fix it. Can someone point me in the right direction? Also the TKinter gui is still a bit new for me so if you have any tips or tricks for me they are well appreciated!
import tkinter
import random
def toonStartscherm():
keuzescherm.pack_forget()
spelerscherm.pack_forget()
startscherm.pack()
def toonKeuzescherm():
keuzescherm.pack()
startscherm.pack_forget()
spelerscherm.pack_forget()
def spelOptie1():
keuzescherm.pack_forget()
startscherm.pack_forget()
spelerscherm.pack()
def randomSpeler():
beginnende_speler = random.choice(['1', '2'])
speler = beginnende_speler
if speler == '1':
speler = '2'
else:
speler = '1'
return str(speler)
def Munt1():
eenMunt = 1
aantal_munten -= eenMunt
def Munt2():
tweeMunt = 2
aantal_munten -= tweeMunt
nim_spel = tkinter.Tk()
global aantal_munten
aantal_munten = 7
startscherm = tkinter.Frame(master=nim_spel)
startscherm.pack()
start_welkom = tkinter.Label(startscherm, text= 'Welkom bij het NIM spel! \nHieronder volgende de spelregels.')
start_welkom.pack()
start_uitleg = tkinter.Label(startscherm, text= 'Het spel NIM start met 7 munten, elke speler mag één of twee munten pakken. \n De speler die de laatste munt pakt verliest!')
start_uitleg.pack() # zet uitleg automatisch in venster
doorgaan_knop = tkinter.Button(startscherm, text = 'Ik snap de regels!', fg = 'green', command = toonKeuzescherm) # maakt knop en laat stoppen
doorgaan_knop.pack(side = 'bottom')
keuzescherm = tkinter.Frame(master=nim_spel)
keuzescherm.pack()
keuze_opties = tkinter.Label(keuzescherm, text='Het NIM spel kan op twee manieren gespeeld worden. \n Optie 1: Tegen elkaar \n Optie 2: Tegen de computer')
keuze_opties.pack() # zet opties automatisch in venster
keuze_vraag = tkinter.Label(keuzescherm, text='Voor welke optie kies je?')
keuze_vraag.pack()
optie_1 = tkinter.Button(keuzescherm, text = 'Optie 1', fg = 'green', command = spelOptie1) # maakt knop en laat stoppen
optie_1.pack(side = 'left')
optie_2 = tkinter.Button(keuzescherm, text = 'Optie 2', fg = 'red', command = keuzescherm.quit) # maakt knop en laat stoppen
optie_2.pack(side = 'right')
spelerscherm = tkinter.Frame(master=nim_spel)
spelerscherm.pack()
beurt_speler = tkinter.Label(spelerscherm, text='Speler ' + (randomSpeler()) + ' is aan de beurt!')
beurt_speler.pack()
munten_over = tkinter.Label(spelerscherm, text='Er zijn nog ' + (str(aantal_munten)) + ' aantal munten over, hoeveel pak je er?')
munten_over.pack()
pak_1_munt = tkinter.Button(spelerscherm, text = '1 munt', fg = 'blue', command = Munt1)
pak_1_munt.pack(side = 'left')
pak_2_munt = tkinter.Button(spelerscherm, text = '2 munten', fg = 'blue', command = Munt2)
pak_2_munt.pack(side = 'right')
toonStartscherm()
nim_spel.mainloop()
def Munt1():
global aantal_munten
eenMunt = 1
aantal_munten -= eenMunt
def Munt2():
global aantal_munten
tweeMunt = 2
aantal_munten -= tweeMunt
I just added the global aantal_munten line and checked it, and it's working perfectly now.
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!
I know that python 2.7 str and bytes are the same(according to Changing string to byte type in Python 2.7)
but I'm using savReaderWriter to write in a .sav file, that is, first column will be a string, and the others are numbers..
my definition is basically the same as in the documentation of savReaderWriter:
savFileName = 'someFile.sav'
records = [[b'Test1', 1, 1], [b'Test2', 2, 1]]
varNames = ['var1', 'v2', 'v3']
varTypes = {'var1': 5, 'v2': 0, 'v3': 0}
with SavWriter(savFileName, varNames, varTypes) as writer:
for record in records:
writer.writerow(record)
on this, they use b'' to convert the string to bytes, but that's a string example, that was written with the code..
but I have a list of strings strings = ["string1", "string2", ...] and each of the strings will be on the my "records"...something like this:
records = [
[strings[0], 0, 0, ...],
[strings[1], 1, 0, ...],
...
]
so, how do I convert the variable to bytes?
I'm getting 'str' object does not support item assigment
Edit: my code: and the traceback "error" that my exception generates is what i've wrote before..
def exporta_sav(matrizes, listas):
#matrizes = [matriz_grupo, matriz_n8]
#listas = [cpcs_grupo, patentes_grupo, cpcs_n8, patentes_n8]
savFile1 = "matrizgrupo.sav"
savFile2 = "matrizsubgrupo.sav"
varTypesGrupo = {}
varTypesNivel8 = {}
stringpatente = 'PATENTE'
#Cria lista auxiliar para fazer a matriz corretamente no formato .sav
varTypesGrupo[stringpatente] = 7
varTypesNivel8[stringpatente] = 7
for i in xrange(len(listas[0])):
varTypesGrupo[listas[0][i]] = 0
for i in xrange(len(listas[2])):
varTypesNivel8[listas[2][i]] = 0
cpcsGrupoAux = [stringpatente]
for i in xrange(len(listas[0])):
cpcsGrupoAux.append(listas[0][i])
cpcsN8Aux = [stringpatente]
for i in xrange(len(listas[2])):
cpcsN8Aux.append(listas[2][i])
#Com as colunas definidas, vai criar listas auxiliares para cada linha
matrizGrupoAux = []
matrizN8Aux = []
if len(matrizes[0]) == len(listas[1]):
for i in xrange(len(matrizes[0])):
matrizGrupoAux.append([ bytes(listas[1][i]) ])
for j in xrange(len(matrizes[0][i])):
matrizGrupoAux[i].append(matrizes[0][i][j])
if len(matrizes[1]) == len(listas[3]):
for i in xrange(len(matrizes[1])):
matrizN8Aux.append([ bytes(listas[3][i]) ])
for j in xrange(len(matrizes[1][i])):
matrizN8Aux[i].append(matrizes[1][i][j])
del listas
del matrizes
#Escrever nos arquivos
try:
with SavWriter(savFile1, cpcsGrupoAux, varTypesGrupo) as writer:
for patente in matrizGrupoAux:
writer.writerows(patente)
with SavWriter(savFile2, cpcsN8Aux, varTypesNivel8) as writer:
for patente in matrizN8Aux:
writer.writerows(patente)
except Exception as error:
print("Ocorreu um erro ao escrever nos arquivos: " + str(error))
Since it's asked, the full traceback(I removed the handling):
Traceback (most recent call last):
File "matrizbinaria.py", line 242, in (module)
exporta_sav(resultados[0], resultados[1])
File "matrizbinaria.py", line 233, in exporta_sav
writer.writerows(patente)
File "C:\Python27\lib\site-packages\savReaderWriter\savWriter.py", line 429 in writerows
self.writerow(record)
File "C:\Python27\lib\site-packages\savReaderWriter\savWriter.py", line 387 in writerow
self._pyWriterow(record)
File "C:\Python27\lib\site-packages\savReaderWriter\savWriter.py", line 379 in _pyWriterow
record[i] = value
TypeError: 'str' object does not support item assignment