I have been trying to make a recursive function, which has two parameters, a word and a list, the list is the symbols of the elements as they are: H for Hydrogen, K for potassium, this is an example of what my program should return : The word Silver can be spelled as SiLvEr.
My function has some errors that I don't have clear how to correct them, I show you my function
def spell_elements(palabra:str , lista:list):
if palabra == "":
return
if palabra[0] in lista:
return palabra[0] spell_elements(palabra.strip(palabra[0]), lista)
elif palabra[:2] in lista:
return palabra[:2] spell_elements(palabra.strip(palabra[:2]), lista)
elif palabra[:3] in lista:
return palabra[:3] spell_elements(palabra.strip(palabra[:3]), lista)
# Example
print(spell_elements("silver", elementos)
# output -> SiLvEr
The program gives me the error "TypeError: can only concatenate str (not "NoneType") to str". I did the debug of the function and it does it correctly but if it does not enter in any condition of the if's and elif's it gives the same problem when it enters in a good way and the word runs out of characters.
CodePudding user response:
The problem is in two places:
Just a raw
returnreturns a value ofNone. So when you callspell_elements()recursively and try to concatenate a string, you get an error. You probably can fix this by doingreturn "".You have
ifwith severalelifbut noelse. If none of the conditions are met, the function terminates when it reaches the end and returnsNoneby default. Again, you can fix this by addingreturn ""at the end of the function.
CodePudding user response:
May be you do not need a function to do it. Just use a 'dict'
elems={
"Silver":"SiLvEr",
"Hydrogen":"H",
"Potassium":"K"}
How to use it
print(elems["Silver"]) # output-> SiLvEr
print(elems["Hidrogen"]) # output-> H
You can extend the dict elems with other elements.
In practice you have a Key and a Value use it as you need
elemS={
"SiLvEr":"Silver",
"H":"Hydrogen",
"K":"Potassium"}
print(elemS["H"]) # output-> Hidrogen
print(elemS["K"]) # output-> Potassium
