Python vs Java DSA: Modulo Operator Differences

Switched from Java to Python for DSA practice. First thing that broke my code? The modulo operator. Not because I didn't know how it works — but because it works differently depending on the language, and I had no idea. In Java/C++, % follows the sign of the dividend: -7 % 3 → -1 In Python, % follows the sign of the divisor: -7 % 3 → 2 I was solving a prefix sum problem. Logic was right, approach was right, wrong answers. Took me embarrassingly long to find it. Once I did, I started noticing more: → Division: Java's 7/2 = 3 (integer). Python's 7/2 = 3.5 (decimal). Use // for integer division. → Floor vs truncate: Java truncates toward zero. Python floors toward negative infinity. -7 // 2 → Java: -3 | Python: -4 Same symbols. Different contracts. No errors thrown. Fewer lines of code. More silent assumptions waiting to bite you. #Python #Java #DSA #LearningInPublic #CompetitiveProgramming

To view or add a comment, sign in

Explore content categories