Codewars:解决Kata - 最高和最低

时间:2016-10-29 05:54:44

标签: python

这应该可以,但是在运行测试用例时我遇到了错误。出于某种原因,第四个失败了。数字[0]打印出'-1'但在分配给highest_number或lowest_number之后只打印出' - '。是什么给了什么?

代码:

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.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");

错误:

ValueError: invalid literal for int() with base 10: '-'

2 个答案:

答案 0 :(得分:1)

首先拆分您的号码,否则您只是将numbers的第一个字符分配给您的变量:

    numbers = numbers.split(" ")
    highest_number = numbers[0]
    lowest_number = numbers[0]

答案 1 :(得分:0)

在这里尝试一下!我刚刚得到它,我觉得很傻,你可以用+符号添加字符串!

答案是:

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))