def high_and_low(numbers: str):
#split function below will use space (' ') as separator
numbers = list(map(int,numbers.split()))
return max(numbers),min(numbers)
def high_and_low(numbers: str):
"""
Given a string of characters, ignore and split on
the space ' ' character and return the min(), max()
:param numbers: input str of characters
:return: the minimum and maximum *character* values as a tuple
"""
return max(numbers.split(' ')), min(numbers.split(' '))
def high_and_low_of_list(numbers: list):
"""
Given a list of values, return the max() and
min()
:param numbers: a list of values to be compared
:return: the min() and max() *integer* values within the list as a tuple
"""
return min(numbers), max(numbers)
def high_and_low(numbers):
# split numbers based on space v
numbers = [int(x) for x in numbers.split()]
# ^ type-cast each element to `int`
return max(numbers), min(numbers)
另一种(更快)使用映射的方法:
为了达到您想要的结果,您可以对传入的字符串调用
split()
。这基本上创建了输入字符串的list()
,您可以在其上调用min()
和max()
函数。正如其他人指出的那样,您还可以传入一个要比较的值的列表,并可以直接在该列表上调用min和max函数。
原始函数在技术上是有效的,但是,它比较的是每个字符的数值,而不仅仅是整数的数值。
您正在将字符串传递给函数。为了获得所需的结果,需要分割字符串,然后将每个元素类型转换为
int
。那么只有min
和max
函数才能正常工作。例如:样本运行:
当前,您的代码正在根据字符的lexicographical order查找最小值和最大值。
相关问题 更多 >
编程相关推荐