Sunday, April 28, 2024
HomeSoftware EngineeringReturning Highest and Lowest in Python

Returning Highest and Lowest in Python


The problem

You’re given a string of space-separated numbers and must return the very best and lowest quantity.

Instance:

high_and_low("1 2 3 4 5")  # return "5 1"
high_and_low("1 2 -3 4 5") # return "5 -3"
high_and_low("1 9 3 4 -5") # return "9 -5"

Notes:

  • All numbers are legitimate Int32, no want to validate them.
  • There’ll at all times be a minimum of one quantity within the enter string.
  • Output string should be two numbers separated by a single house, and highest quantity is first.

The answer in Python code

Possibility 1:

def high_and_low(numbers):
    nums = sorted([int(x) for x in numbers.split(" ")], reverse=True)
    return str(nums[0])+" "+str(nums[-1])

Possibility 2:

def high_and_low(numbers):
    n = map(int, numbers.cut up(' '))
    return str(max(n)) + ' ' + str(min(n))

Possibility 3:

def high_and_low(numbers):
    nums = sorted(numbers.cut up(), key=int)
    return '{} {}'.format(nums[-1], nums[0])

Check instances to validate our answer

import check
from answer import high_and_low

@check.describe("Mounted Checks")
def fixed_tests():
    @check.it('Fundamental Check Instances')
    def basic_test_cases():
        check.assert_equals(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"), "542 -214");
        check.assert_equals(high_and_low("1 -1"), "1 -1");
        check.assert_equals(high_and_low("1 1"), "1 1");
        check.assert_equals(high_and_low("-1 -1"), "-1 -1");
        check.assert_equals(high_and_low("1 -1 0"), "1 -1");
        check.assert_equals(high_and_low("1 1 0"), "1 0");        
        check.assert_equals(high_and_low("-1 -1 0"), "0 -1");
        check.assert_equals(high_and_low("42"), "42 42");
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments