w3resource

Python: Sort three integers without using conditional statements and loops


Sort Three Numbers

Write a Python program to sort three integers without using conditional statements and loops.

Pictorial Presentation:

Sort three integers without using conditional statements and loops

Sample Solution:

Python Code:

# Prompt the user to input three integers and convert them to variables x, y, and z.
x = int(input("Input first number: "))
y = int(input("Input second number: "))
z = int(input("Input third number: "))

# Find the minimum value among x, y, and z and store it in variable a1.
a1 = min(x, y, z)

# Find the maximum value among x, y, and z and store it in variable a3.
a3 = max(x, y, z)

# Calculate the middle value (not the minimum or maximum) by subtracting a1 and a3 from the sum of x, y, and z.
a2 = (x + y + z) - a1 - a3

# Print the numbers in sorted order (a1, a2, a3).
print("Numbers in sorted order: ", a1, a2, a3)

Sample Output:

Input first number: 2                                                                                         
Input second number: 4                                                                                        
Input third number: 5                                                                                         
Numbers in sorted order:  2 4 5 

Flowchart:

Flowchart: Sort three integers without using conditional statements and loops.

For more Practice: Solve these Related Problems:

  • Write a Python program to sort four numbers without using loops or conditional statements.
  • Write a Python program to swap the values of three variables without using a temporary variable.
  • Write a Python program to sort three floating-point numbers in ascending order without using built-in functions.
  • Write a Python program to sort three numbers using bitwise operations.

Python Code Editor:

 

Previous: Write a Python program to calculate the sum of the digits in an integer.
Next: Write a Python program to sort files by date.

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.