For example, to check if they are greater than, lesser than or equal to each other without using int() and def.
num1 = "67"
num2 = "1954"
Timur Shtatland
12.6k3 gold badges40 silver badges66 bronze badges
2 Answers 2
Left pad with zero and then compare the strings lexicographically:
num1 = "67"
num2 = "1954"
if num1.zfill(10) < num2.zfill(10):
print("67 is less than 1954")
Note here that the left padding trick leaves the 2 numbers with the same string length. So we are doing something like comparing 0067
to 1954
, in which case the dictionary order is in agreement with the numerical order.
answered Jul 9, 2021 at 13:22
5 Comments
user2390182
What about negative numbers?
desperate
what if the user inputs a number and you don't know what the len() would be?
Tim Biegeleisen
@schwobaseggl Good edge case, I hadn't thought of this. The padding logic would get more complex.
user2390182
Yeah, also then the lexicographic order must be reversed. That's quite awkward
Tim Biegeleisen
@desperate Assuming your above comment be directed at me, you may just choose a large enough padding. There probably isn't any real upper limit to the size of the padding.
Easiest without padding to an unknown length:
if (len(num1), num1) < (len(num2), num2):
print(num1, "<", num2)
answered Jul 9, 2021 at 13:26
4 Comments
desperate
it is not needed for negative numbers
desperate
can you explain the purpose of putting the variable after the comma in the brackets, for eg (len(num1), num1)? I am new to this
user2390182
Instead of only the strings, you compare tuples (pairs) of length and string, in your example:
(2, "67") < (4, "1954")
. Tuple comparison works lexicographically, as well, in that the second elements are only compared if the first elements are the same. Hence, shorter numbers will always be considered smaller. Numbers of equal length will be compared alphabetically.ekhumoro
This method fails for e.g.
num1 = '4'; num2 = '03'
.Explore related questions
See similar questions with these tags.
lang-py
int
?