This should work but I'm getting errors when running the test cases. For some reason the fourth one fails. numbers[0] prints out '-1' but after assigning to highest_number or lowest_number only the '-' prints out. What gives?
Code:
def high_and_low(numbers):
if numbers:
highest_number = numbers[0]
lowest_number = numbers[0]
numbers = numbers.split(" ")
print(highest_number)
print(lowest_number)
print(numbers[0])
for num in numbers:
if int(num) > int(highest_number):
highest_number = num
if int(num) < int(lowest_number):
lowest_number = num
return highest_number + " " + lowest_number
Test Cases:
Test.assert_equals(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"), "542 -214");
Test.assert_equals(high_and_low("1 -1"), "1 -1");
Test.assert_equals(high_and_low("1 1"), "1 1");
Test.assert_equals(high_and_low("-1 -1"), "-1 -1");
Test.assert_equals(high_and_low("1 -1 0"), "1 -1");
Test.assert_equals(high_and_low("1 1 0"), "1 0");
Test.assert_equals(high_and_low("-1 -1 0"), "0 -1");
Test.assert_equals(high_and_low("42"), "42 42");
Error:
ValueError: invalid literal for int() with base 10: '-'
Split your numbers first, else you are just assigning the first character of numbers
to your variables:
numbers = numbers.split(" ")
highest_number = numbers[0]
lowest_number = numbers[0]
Here try this! I just got it, I feel so silly, you can add strings with the +
sign!
Answer is:
def high_and_low(numbers):
# must split the numbers, convert them to integers and print the max and min of list
numbers = numbers.split()
numbers = [int(i) for i in numbers]
return str(max(numbers))+" "+str(min(numbers))
you can use this code:
def high_and_low(numbers):
nn = [int(s) for s in numbers.split(" ")]
return "%i %i" % (max(nn),min(nn))
and done
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.