w3resource

Python: Compute the digit distance between two integers

Python Basic - 1: Exercise-112 with Solution

Write a Python program to compute the digit distance between two integers.
The digit distance between two numbers is the absolute value of the difference of those numbers.
For example, the distance between 3 and −3 on the number line given by the |3 – (−3) | = |3 + 3 | = 6 units
Digit distance of 123 and 256 is
Since |1 - 2| + |2 - 5| + |3 - 6| = 1 + 3 + 3 = 7

Sample Solution:

Python Code:

def digit_distance_nums(num1: int, num2: int) -> int:
  return(sum(abs(i - j) for i, j in
  zip(map(int, str(num1)), map(int, str(num2)))))
print(digit_distance_nums(509, 510))
print(digit_distance_nums(123, 256))
print(digit_distance_nums(23, 56))
print(digit_distance_nums(1, 2))
print(digit_distance_nums(24232, 45645))

Sample Output:

10
7
6
1
11

Flowchart:

Flowchart: Python - Compute the digit distance between two integers.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to check whether two given circles (given center (x,y) and radius) are intersecting.
Next: Write a Python program to reverse all the words which have even length.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.