2

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
asked Jul 9, 2021 at 13:17
4
  • 3
    Why wouldn't you use int? Commented Jul 9, 2021 at 13:21
  • the question specifies not to use it Commented Jul 9, 2021 at 13:22
  • Why would the question specify not to use it? Commented Jul 9, 2021 at 13:24
  • Would you need this to work for negative numbers? Commented Jul 9, 2021 at 13:28

2 Answers 2

5

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

What about negative numbers?
what if the user inputs a number and you don't know what the len() would be?
@schwobaseggl Good edge case, I hadn't thought of this. The padding logic would get more complex.
Yeah, also then the lexicographic order must be reversed. That's quite awkward
@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.
1

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

it is not needed for negative numbers
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
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.
This method fails for e.g. num1 = '4'; num2 = '03'.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.