I'm trying to figure this out.... | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 1

I'm trying to figure this out....

I'm trying to create a simple code decoder. More specifically, I'm trying to take input and replace that input with the dictionary reference (x:y) only printing out 'y' decoder = {'a': '!', 'b': '@', 'c': '#', 'd': '

#x27;, 'e': '%'} num = str(input("What is your code?")) def code(secret): rom= '' for k, v in decoder.items(): if secret == k: rom += v return rom print(code(num))

30th Apr 2018, 7:13 PM
Jeff Myers
Jeff Myers - avatar
9 Respuestas
+ 3
Here Viking Rey. This code does it. Let me know if you need any explaining. https://code.sololearn.com/c658f0GEW81A/?ref=app
30th Apr 2018, 8:29 PM
cyk
cyk - avatar
+ 3
It should work for one-char input. Otherwise, if you want to replace all characters with decoded items, you have to iterate through the whole string. Or use str.replace ;) BTW, input() already returns string by default, no need to over-cast it.
30th Apr 2018, 7:29 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 3
Kuba wasn't talking to you but to Prime, the guy who posted the web code in the comments
30th Apr 2018, 8:20 PM
cyk
cyk - avatar
+ 2
Hello Viking! I made a small change to the code. I commented the other definition of the function and defined a new one. Fact is I have a thing against nested loops and was thinking that for each letter we really do not need to check every single key, value pair. The time complexity of that can get really nasty if you have lots of decoding to do. So, I used the .get(key) method of dictionaries instead. That method has technically time complexity O(1) which is the best you can get. This is more compact and does less uneeded iterations.
30th Apr 2018, 9:22 PM
cyk
cyk - avatar
+ 1
Want to hear something funny? Your code does work. It's just that it writes the output right after your question: What is your code? So makes it hard to see. Look right after the question mark when you run it you will see what I mean So, I would advice writing input("What is your code?\n") so the next print will be done on the next line And you don't need to do str(input())... input() already gets the input as a string always
30th Apr 2018, 7:26 PM
cyk
cyk - avatar
+ 1
Thanks cyk I really appreciate it. It's very understandable.
30th Apr 2018, 8:35 PM
Jeff Myers
Jeff Myers - avatar
0
posting everywhere? I posted it once.
30th Apr 2018, 8:19 PM
Jeff Myers
Jeff Myers - avatar
0
Okay. Yeah I'm trying to iterate through the input string. How can I accomplish that?
30th Apr 2018, 8:20 PM
Jeff Myers
Jeff Myers - avatar
0
cyk
30th Apr 2018, 8:31 PM
Atik
Atik - avatar