I want to make a deck out of tarjeta, but i cant seem to print it and i cant use index. The Class Tarjeta works but when i append it to Mazo and print it, it gives me the same thing as if i didnt have the str thingy.
paises_por_tarjeta is a {}
class Tarjeta(object): #this is ClassA
"""Implementacion de una tarjeta de pais."""
def __init__(self, pais=None, tipo=0):
"""Constructor desde pais y tipo."""
self.pais = pais
self.tipo = tipo
def __str__(self):
"""Representacion grafica."""
return "(%s,%s)"%(self.pais, NOMBRE_TARJETAS[self.tipo])
class Mazo(object): #ClassB
"""Implementacion del mazo de tarjetas de pais."""
def __init__(self, paises_por_tarjeta): #paises_por_tarjeta is a {} that has the suit as key and countries as value
"""Creacion desde un diccionario de paises segun tipo.
Debe inicializar el mazo con todas las tarjetas mezcladas."""
self.mazo=[]
for i in range(0,4):
for x in paises_por_tarjeta[i]:
self.mazo.append(Tarjeta(x,i))
max_cartas=len(self.mazo)
for k in range(max_cartas): #mezcla el mazo
j=random.randrange(k,max_cartas)
self.mazo[k],self.mazo[j]=self.mazo[j],self.mazo[k]
def __str__(self):
return str(self.mazo)
EDIT: here are the NOMBRE_TARJETAS and paises_por_tarjeta:
TARJETA_COMODIN = 0
TARJETA_GALEON = 1
TARJETA_GLOBO = 2
TARJETA_CANON = 3
NOMBRE_TARJETAS = {
TARJETA_COMODIN: 'comodin',
TARJETA_GALEON: 'galeon',
TARJETA_GLOBO: 'globo',
TARJETA_CANON: 'canon',
}
paises_por_tarjeta = {
TARJETA_COMODIN: ['Argentina', 'Taimir'],
TARJETA_GALEON: ['Alaska', 'Alemania', 'Borneo', 'Brasil', 'China', 'Gran Bretana', 'Groenlandia', 'Islandia', 'Israel', 'Madagascar', 'Mongolia', 'Nueva York', 'Peru', 'Siberia', 'Suecia', 'Turquia', 'Zaire'],
TARJETA_GLOBO: ['Chile', 'Colombia', 'Egipto', 'Espana', 'Etiopia', 'Francia', 'Gobi', 'India', 'Iran', 'Italia', 'Kamchatka', 'Rusia', 'Sumatra', 'Uruguay', 'Yukon'],
TARJETA_CANON: ['Arabia', 'Aral', 'Australia', 'California', 'Canada', 'Japon', 'Java', 'Labrador', 'Malasia', 'Mexico', 'Oregon', 'Polonia', 'Sahara', 'Sudafrica', 'Tartaria', 'Terranova'],
}
Any help would be appreciated, thanks!
You can try using this __str__ implementation for Mazo:
def __str__(self):
return str([str(k) for k in self.mazo])
Edit: If you want your class to support indexing, you can implement the method __getitem__:
def __getitem__(self, index):
return self.mazo[index]
Related
While creating a tkinter GUI application, I created a window with a button to close the program and terminate the script, but when I used it, the program did close but the script was still running in the background and I was unable to start the program again.
I have tried several different functions to close the program, but nothing has worked. Here are some of my attempts:
def Cerrar():
summary.destroy()
No = customtkinter.CTkButton(summary, text="Cerrar", command=Cerrar,width=10)
or
No = customtkinter.CTkButton(summary, text="Cerrar", command=lambda:Cerrar(),width=10)
or
No = customtkinter.CTkButton(summary, text="Cerrar", command=lambda:summary.destroy(),width=10)
here is the window im having a problem with:
def Analisis():
global resumen,cuantia,summary,refuerzo
Denom_Malla = "{}-{}".format(Malla.get(),Separacion.get())
denominacion_mallas = ["4-25","4-20","4-15","4.5-15","5-15","5.5-15",
"6-15","6.5-15","7-15","7.5-15","8-15","8.5-15",
"4-12.5","4-10","4-7.5","4.5-7.5","5-7.5","5.5-7.5",
"6-7.5","6.5-7.5","7-7.5","7.5-7.5","8-7.5","8.5-7.5"]
if Denom_Malla in denominacion_mallas:
fc = int(Fc.get())
fy_malla = int(Fy_Malla.get())
fy_barra = int(Fy_Barra.get())
mu = float(Mu.get())
H = float(h.get())
Rec = float(rec.get())
malla = Malla.get()
separacion = Separacion.get()
denom_barra = int(Denom_Barra.get())
resumen, cuantia_calculada, d, Rn, cuantia_min, cuantia_diseño, As,Sep_Barra = Calculo_Losa(fc, fy_malla, fy_barra, mu, H, Rec, malla, separacion, denom_barra)
root.destroy()
if resumen == None:
root_losas(lista_fc.index(str(fc)),lista_fy.index(str(fy_malla)),lista_fy.index(str(fy_barra)),lista_mallas.index(malla),lista_denombarra.index(str(denom_barra)),mu,H,Rec,lista_separacion.index(str(separacion)))
else:
summary = customtkinter.CTk()
summary.title("Resumen")
summary.minsize(width=300,height=150)
customtkinter.CTkLabel(summary, text="Momento Último calculado es de: {} KN-m".format(mu)).grid(row=0,column=0,columnspan=2)
customtkinter.CTkLabel(summary, text="La cuantía calculada es de: {}".format(round(cuantia_diseño,4))).grid(row=1,column=0,columnspan=2)
customtkinter.CTkLabel(summary, text="Para la losa se necesita una malla {}".format(resumen)).grid(row=2,column=0,columnspan=2)
customtkinter.CTkLabel(summary, text="Desea realizar otro análisis?").grid(row=3,column=0,columnspan=2)
customtkinter.CTkLabel(summary, text="En que tipo de refuerzo desea guardar: ").grid(row=2,column=3)
refuerzo = customtkinter.StringVar(value=lista_refuerzo[0])
refuerzo_Box = customtkinter.CTkOptionMenu(summary, variable=refuerzo, values=lista_refuerzo, width=100)
refuerzo_Box.grid(row=3,column=3,padx=15)
refuerzo_Box.configure(cursor="hand2")
Yes = customtkinter.CTkButton(summary, text="Analizar", command=lambda:Siguiente(fc,fy_malla,fy_barra,malla,denom_barra,mu,H,Rec,separacion),width=10)
Yes.grid(row=4,column=0)
Yes.configure(cursor="hand2")
Guardar = customtkinter.CTkButton(summary, text="Guardar", command=lambda:Save(fc,fy_malla,mu,1,H,Rec,d,Rn,cuantia_calculada,cuantia_min,cuantia_diseño,As,malla,separacion,denom_barra,Sep_Barra,resumen))
Guardar.grid(row=4,column=3,pady=15)
Guardar.configure(cursor="hand2")
No = customtkinter.CTkButton(summary, text="Cerrar", command=Cerrar,width=10)
No.grid(row=4,column=1)
No.configure(cursor="hand2")
summary.mainloop()
else:
tk.messagebox.showerror(title="Error Malla", message="La denominacion de la malla elegida no está registrada.")
`
all_currencies = currency_api('latest', 'currencies') # {'eur': 'Euro', 'usd': 'United States dollar', ...}
all_currencies.pop('brl')
qtd_moedas = len(all_currencies)
texto = f'{qtd_moedas} Moedas encontradas\n\n'
moedas_importantes = ['usd', 'eur', 'gbp', 'chf', 'jpy', 'rub', 'aud', 'cad', 'ars']
while len(moedas_importantes) != 0:
for codigo, moeda in all_currencies.items():
if codigo == moedas_importantes[0]:
cotacao, data = currency_api('latest', f'currencies/{codigo}/brl')['brl'], currency_api('latest', f'currencies/{codigo}/brl')['date']
texto += f'{moeda} ({codigo.upper()}) = R$ {cotacao} [{data}]\n'
moedas_importantes.remove(codigo)
if len(moedas_importantes) == 0: break # WITHOUT THIS LINE, GIVES ERROR
Why am I getting this error? the list actually runs out of elements, but the code only works with the if
You have a nested loop. The while loop is entered and then execution immediately starts in the for loop. Execution remains in the for loop for all elements in all_currencies.items(). Each time codigo is found at the beginning of moedas_importantes, that element is removed. Eventually you remove all elements from moedas_importantes, but you are still in the for loop and check if codigo == moedas_importantes[0]. At this point moedas_importantes is empty so you get an index error.
I think the below code will work without the nested loops. Note, this assumes all elements in moedas_importantes are also keys in all_currencies.
all_currencies = currency_api('latest', 'currencies') # {'eur': 'Euro', 'usd': 'United States dollar', ...}
all_currencies.pop('brl')
qtd_moedas = len(all_currencies)
texto = f'{qtd_moedas} Moedas encontradas\n\n'
moedas_importantes = ['usd', 'eur', 'gbp', 'chf', 'jpy', 'rub', 'aud', 'cad', 'ars']
while len(moedas_importantes) != 0:
codigo = moedas_importantes[0]
moeda = all_currencies[codigo]
cotacao, data = currency_api('latest', f'currencies/{codigo}/brl')['brl'], currency_api('latest', f'currencies/{codigo}/brl')['date']
texto += f'{moeda} ({codigo.upper()}) = R$ {cotacao} [{data}]\n'
moedas_importantes.remove(codigo)
I have a conditional dict, when a string is recognized thorugh a function, it returns the key of that dictionary.
The dict is "myDict", which will be use together with the list "lookup", find a word that exists in it, and return the dictionary key for that list, adding it to the end of that name.
My code:
myDict = {'NESTLE':
['NESFIT', 'NESCAU', 'DOIS FRADES', 'MOCA', 'KIT KAT', 'NESQUIK', 'ALPINO', 'LEITE CONDENSADO MOCA'
'CHAMYTO', 'NINHO', 'MOLICO', 'CHAMBINHO', 'CHANDELLE', 'BONO', 'PASSATEMPO', 'KITKAT', 'CLASSIC'],
'all_names': ['rodis', 'Stone', 'abx']}
def search(myDict, lookup):
for key, value in myDict.items():
for v in value:
if lookup in v:
return key
lookup = ['NESCAU', 'Confeito coberto de chocolate ao leite NESCAU Ball', 'NESCAU EM PO', 'Stone']
lookup2 = [str(x).split(' ') for x in lookup]
for x in range(0, len(lookup)):
finder = search(myDict, lookup[x])
print(finder)
NESTLE
None
None
all_names
I arrived here, but was unable to do this output with the dictinary's key at the end of the list, and it is not searching for all words that contains in it, thus I wanted this output:
output_lookup = ['NESCAU NESTLE', 'Confeito coberto de chocolate ao leite NESCAU Ball NESTLE', 'NESCAU EM PO NESTLE', 'Stone all_names']
I changed your code.
I added a split of the lookup string.
myDict = {'NESTLE':
['NESFIT', 'NESCAU', 'DOIS FRADES', 'MOCA', 'KIT KAT', 'NESQUIK', 'ALPINO', 'LEITE CONDENSADO MOCA'
'CHAMYTO', 'NINHO', 'MOLICO', 'CHAMBINHO', 'CHANDELLE', 'BONO', 'PASSATEMPO', 'KITKAT', 'CLASSIC'],
'all_names': ['rodis', 'Stone', 'abx']}
def search(myDict, lookup):
for key, value in myDict.items():
for v in value:
# if lookup in v:
if v in lookup.split(' '):
return key
lookup = ['NESCAU', 'Confeito coberto de chocolate ao leite NESCAU Ball', 'NESCAU EM PO', 'Stone']
lookup2 = [str(x).split(' ') for x in lookup]
for x in lookup:
finder = search(myDict, x)
print(f"{x} {finder}")
Here the output that i got
NESCAU NESTLE
Confeito coberto de chocolate ao leite NESCAU Ball NESTLE
NESCAU EM PO NESTLE
Stone all_names
this issue appear when I put promedios[x] = float(punteos / 3), if suppose to x is in for outside have a int value like possition. I modified the code with the new changes
def alumno(nombre, apellido):
print('Nombre: ', nombre, 'Apellido: ', apellido)
def promedio(a,b,c):
promedio1 = int(a+b+c)/3
#return promedio1
print(promedio1)
nombre = input('ingrese nombre: ')
apellido = input('ingrese apellido: ')
alumno(nombre,apellido)
print()
#promedio(1,2,3)
print('Ingrese los punteos de las Materias:')
punteo = 0
materias = 5
for x in range(0, materias):
punteos = 0
notas = 3
promedio1 = 0
promedios = []
xx = 1
for y in range(0, notas):
punteo = int(input("Ingrese punteo de la Materia "+str(x+1)+" punteo "+str(y+1)+": "))
punteos = int(punteos + punteo)
promedio1 = float(punteos/3)
promedios.append(promedio1)
print('El promedio de la materia ',x+1,' es ',promedio1)
print(promedios[x])
As long as you have done promedios = 0 and no longer modify the variable promedios before the line of code promedios[x] = float(punteos / 3), promedios is an int at that line.
However, doing promedios[x] = ... calls the __setitem__ method of variable promedios, which is of type int and of course does not support such item assignment.
Types like list, dict support item assignment, by the way.
You need to start with an empty list:
promedios = []
And then append to it:
promedios.append(float(punteos / 3))
I want an activity to scrapy a web page. The part of data web is route_data.
route_data = ["javascript:mostrarFotografiaHemiciclo( '/wc/htdocs/web/img/diputados/peq/215_14.jpg', '/wc/htdocs/web', 'Batet Lamaña, Meritxell (Presidenta del Congreso de los Diputados)', 'Diputada por Barcelona', 'G.P. Socialista' ,'','');",
"javascript:mostrarFotografiaHemiciclo( '/wc/htdocs/web/img/diputados/peq/168_14.jpg', '/wc/htdocs/web', 'Rodríguez Gómez de Celis, Alfonso (Vicepresidente Primero)', 'Diputado por Sevilla', 'G.P. Socialista' ,'','');",]
I create a dictionary with empty values.
dictionary_data = {"Nombre":None, "Territorio":None, "Partido":None, "url":None}
I have to save in dictionary_data each one line:
url = /wc/htdocs/web/img/diputados/peq/215_14.jpg
Nombre = Batet Lamaña, Meritxell
Territorio = Diputada por Barcelona
Partido = G.P. Socialista
For thus, and I loop over route_data.
for i in route_data:
text = i.split(",")
nombre = text[2:4]
territorio = text[4]
partido = text[5]
But the output is:
[" 'Batet Lamaña", " Meritxell (Presidenta del Congreso de los Diputados)'"] 'Diputada por Barcelona' 'G.P. Socialista'
[" 'Rodríguez Gómez de Celis", " Alfonso (Vicepresidente Primero)'"] 'Diputado por Sevilla' 'G.P. Socialista'
How can it get put correct in dictionary?
A simple solution would be:
all_routes = []
for i in route_data:
text = re.findall("'.+?'", i)
all_routes.append(
{"Nombre": re.sub('\(.*?\)', '', text[2]).strip(),
"Territorio": text[3],
"Partido": text[-2],
"Url": text[0]})