|
So I am new to Python. But I am convinced there is something wierdness about % operator. Becuase 3%5 and -3%5 give two different results. So anyway I used abs function and prefixed the sign. But looks like this si so wierd a programming language would behave like this (3%5 gives 3 and -3%5 gives 2) OK I agree with explanation of "fnenu" on how python is doing this. For a while I thought I have gone insane so I did the same exact thing in C# and Java. Well the answer for -3%5 in java and c# is -3. So that si good at least i have not gone crazy with this basic stuff. Sounds like some differences in the language. Anyway I am not going to labor over this. Accept how python is doing this and move on Now wonder if Python is weird or other languages are weird :) I will leave it at that |
There is a nice table here at Wikipedia showing how it works in a large number of languages. |
|
OK I agree with explanation of "fnenu" on how python is doing this. For a while I thought I have gone insane so I did the same exact thing in C# and Java. Well the answer for -3%5 in java and c# is -3. So that si good at least i have not gone crazy with this basic stuff. Sounds like some differences in the language. Anyway I am not going to labor over this. Accept how python is doing this and move on So I was trying to do sth like this (p[-U:]+p[:-U]).. Anyway solved it by abs value..But AS I saw the solution looks like there is a better way to do this 2
Well as I understood that, it that if you have modulo 5, you have a world where you go like this -5 -4 -3 -2 -1 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 4 0 On the right side of the zero it's quite clear - you have 0/5, 1/5. On the left side it's different. But basically as you go on the axis to the left direction, you see that -3 in the decimal numbers maps to 2 in modulo 5 1
Yah..Now I am starting to think after all may be python is doing it the cool way and all these other languages have wired me into wrong way anyway..I will leave it at that So if what you're saying about C# and Java is true, Wikipedia has it wrong:
For everything that implies a wraparound, it's clearly the modulo that we want, not the division remainder. Ruby and Javascript use And the Python Language Reference has it wrong too!
What's going on here? |
|
Since I come mostly from PHP world and this is my first close encounter with python, I was also confused when I saw a one-liner code for looking up the position index in the solution :-) But anyway I find it a rather cool feature of python, since mathematically it gives sense - meaning that when using modulo, the world is consisting only of 0 1 2 3 4 series and -3 is mapped to 2 in this world. Where as far as I know in c-style languages you could use at most something like ternary operator. I am kind of curious what other surprises is python going to bring :-D |