w3resource

Python: Find the highest and lowest number from a given string of space separated integers

Python Basic - 1: Exercise-97 with Solution

Write a Python program to find the highest and lowest number from a given string of space-separated integers.

Sample Solution:

Python Code:

# Define a function named highest_lowest_num that takes a string of numbers (str1) as an argument.
def highest_lowest_num(str1):
    # Convert the string of numbers into a list of integers using map and split.
    num_list = list(map(int, str1.split()))
    
    # Return the maximum and minimum values in the list.
    return max(num_list), min(num_list)

# Test the function with different strings of numbers and print the results.

# Test case 1
text = "1 4 5 77 9 0"
# Print the original string of numbers.
print("Original string:", text)
# Print the highest and lowest numbers in the string.
print("Highest and lowest number of the said string:", highest_lowest_num(text))

# Test case 2
text = "-1 -4 -5 -77 -9 0"
# Print the original string of numbers.
print("\nOriginal string:", text)
# Print the highest and lowest numbers in the string.
print("Highest and lowest number of the said string:", highest_lowest_num(text))

# Test case 3
text = "0 0"
# Print the original string of numbers.
print("\nOriginal string:", text)
# Print the highest and lowest numbers in the string.
print("Highest and lowest number of the said string:", highest_lowest_num(text))

Sample Output:

Original string: 1 4 5 77 9 0
Highest and lowest number of the said string: (77, 0)

Original string: -1 -4 -5 -77 -9 0
Highest and lowest number of the said string: (0, -77)

Original string: 0 0
Highest and lowest number of the said string: (0, 0)

Explanation:

Here is a breakdown of the above Python code:

  • Function definition:
    • The code defines a function named "highest_lowest_num()" that takes a string of numbers (str1) as an argument.
  • List conversion:
    • The function converts the string of numbers into a list of integers using 'map' and 'split'.
  • Return Statement:
    • The function returns the maximum and minimum values in the list.

Visual Presentation:

Python: Find the highest and lowest number from a given string of space separated integers.
Python: Find the highest and lowest number from a given string of space separated integers.

Flowchart:

Flowchart: Python - Find the highest and lowest number from a given string of space separated 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 a given number is a narcissistic number or not.
Next: Write a Python program to check whether a sequence of numbers has an increasing trend or not.

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.