+ 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))9 ответов
+ 3
Here Viking Rey. This code does it. Let me know if you need any explaining.
https://code.sololearn.com/c658f0GEW81A/?ref=app
+ 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.
+ 3
Kuba wasn't talking to you but to Prime, the guy who posted the web code in the comments
+ 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.
+ 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
+ 1
Thanks cyk I really appreciate it. It's very understandable.
0
posting everywhere? I posted it once.
0
Okay. Yeah I'm trying to iterate through the input string.
How can I accomplish that?
0
cyk