w3resource

Python: Find the difference between the largest integer and the smallest integer which are created by 8 numbers from 0 to 9

Python Basic - 1: Exercise-51 with Solution

Write a Python program that determines the difference between the largest and smallest integers created by 8 numbers from 0 to 9. The number that can be rearranged shall start with 0 as in 00135668.

Input:
Data is a sequence of 8 numbers (numbers from 0 to 9).
Output:
The difference between the largest integer and the smallest integer.

Visual Presentation:

Python: Find the difference between the largest integer and the smallest integer which are created by 8 numbers from 0 to 9

Sample Solution:

Python Code:

# Print statement to prompt the user to input an integer created by 8 numbers from 0 to 9
print("Input an integer created by 8 numbers from 0 to 9.:")

# Convert the input integer to a list of characters
num = list(input())

# Print statement to calculate and display the difference between the largest and smallest integer from the given integer
print("Difference between the largest and the smallest integer from the given integer:")

# Convert the list of characters to integers after sorting in ascending and descending order
# Calculate the difference between the largest and smallest integers and print the result
print(int("".join(sorted(num, reverse=True))) - int("".join(sorted(num))))

Sample Output:

Input an integer created by 8 numbers from 0 to 9.:
 34568729
Difference between the largest and the smallest integer from the given integer:
75308643

Explanation:

Here is a breakdown of the above Python code:

  • The above code prompts the user to input an integer created by 8 numbers from 0 to 9.
  • User input is converted into a list of characters.
  • The code calculates the difference between the largest and smallest integers created from the given input.
  • Finally the result is printed.

Flowchart:

Flowchart: Python - Find the difference between the largest integer and the smallest integer which are created by 8 numbers from 0 to 9

Python Code Editor:

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

Previous: Write a Python program to replace a string "Python" with "Java" and "Java" with "Python" in a given string.
Next: Write a Python program to compute the sum of first n given prime numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/basic/python-basic-1-exercise-51.php