Why the remainder is 3? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why the remainder is 3?

Here I used a dictionary x={1:2,2:3,3:4,4:6} And I printed as below >>>print(x.get(2,0)%x.get(5,4)) >>>3 Why it prints 3,as my dictionary as no 5 as Key ? https://code.sololearn.com/csYeHsPoWs22/?ref=app

5th Aug 2020, 3:29 PM
Samba_Chinta
Samba_Chinta - avatar
5 Answers
+ 10
Your expression is: x={1:2,2:3,4:1,3:5} print(x.get(2,0)%x.get(5,4)) -> x.get(2,0) -> 3 -> x.get(5,4) -> 4, as there is no key 5 -> 3 % 4 -> 3 // 4 -> 0 , and there is a remainder of 3 left. you can check it by using divmod: divmod(3,4) (0, 3) division gives -> 0, remainder gives -> 3
5th Aug 2020, 3:41 PM
Lothar
Lothar - avatar
+ 6
I have simplified the code by using more steps. When using the following link, you will get to the web site of pythontutor, and you can see the code. Then you can start and move in visual steps through the code. use the "next" button to execute the code step by step. http://www.pythontutor.com/visualize.html#code=x%3D%7B1%3A2,2%3A3,3%3A4,4%3A6%7D%0Ares1%20%3D%20x.get%282,0%29%0Ares2%20%3D%20x.get%285,4%29%0Aprint%28res1%20%25%20res2%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false
5th Aug 2020, 7:00 PM
Lothar
Lothar - avatar
+ 4
The second argument passed to the get() method is the default value that will be used when the first argument (key) doesn't exist. Your print statement evaluates to: print(3 % 4) 3 / 4 = 0 with a remainder of 3
5th Aug 2020, 3:36 PM
ChaoticDawg
ChaoticDawg - avatar
+ 3
Samba, because you provide as second argument of the get method 4 as default value if there is no such key in your dictionary. You can find more info here:https://www.tutorialspoint.com/JUMP_LINK__&&__python__&&__JUMP_LINK/dictionary_get.htm
5th Aug 2020, 3:34 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
0
Is it append that not found key with value to dictionary..?
5th Aug 2020, 3:55 PM
Samba_Chinta
Samba_Chinta - avatar