w3resource

Python: Compute the digit distance between two integers


Digit Distance Calculator

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:

# Define a function named digit_distance_nums that calculates the sum of digit distances between two numbers.
def digit_distance_nums(num1: int, num2: int) -> int:
    # Use the zip function to pair corresponding digits from the two numbers.
    # Use map(int, str(num)) to convert each number into a list of its digits.
    # Calculate the absolute difference between corresponding digits and sum them up.
    return sum(abs(i - j) for i, j in zip(map(int, str(num1)), map(int, str(num2))))
	
# Test the function with different pairs of numbers and print the results.

# Test case 1
print(digit_distance_nums(509, 510))

# Test case 2
print(digit_distance_nums(123, 256))

# Test case 3
print(digit_distance_nums(23, 56))

# Test case 4
print(digit_distance_nums(1, 2))

# Test case 5
print(digit_distance_nums(24232, 45645)) 

Sample Output:

10
7
6
1
11

Explanation:

Here is a breakdown of the above Python code:

  • Function definition:
    • The code defines a function named "digit_distance_nums()" that calculates the sum of digit distances between two numbers.
  • Digit pairing:
    • The zip function is used to pair corresponding digits from the two numbers.
    • map(int, str(num)) is used to convert each number into a list of its digits.
  • Digit distance calculation:
    • The absolute difference between the corresponding digits is calculated using abs(i - j).
  • Summation:
    • The sum of absolute differences is calculated using sum(...).
  • Test cases:
    • The function is tested with different pairs of numbers, and the results are printed using print(digit_distance_nums(...)).

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.