我缺少打印能力
"The median cannot be found"
基于序列中没有任何内容。这是我当前使用None的代码,该代码不起作用。
def print_median(seq):
if print_median(sep) = None:
print("The median cannot be found.")
else:
median = (seq[len(seq) // 2 - 1] + seq[len(seq) // 2]) / 2
print("The median of " + str(seq) + " is " + str(median) + ".")
也尝试使用((),)和一些不起作用的随机尝试。 预期结果是
>>> print_median(())
The median cannot be found.
以及生产
>>> print_median((-12, 0, 3, 9))
The median of (-12, 0, 3, 9) is 1.5.
用于在序列中输入数字时。
答案 0 :(得分:2)
按照惯例,Python序列只有且为空时才是虚假的。
if seq:
...
else:
print("The median cannot be found.")
答案 1 :(得分:1)
如果将函数限制为sequence,则可以测试False的序列,因为空容器在Python中是False
:
def print_median(seq):
if not seq:
print("The median cannot be found.")
else:
median = (seq[len(seq) // 2 - 1] + seq[len(seq) // 2]) / 2
print("The median of " + str(seq) + " is " + str(median) + ".")
The仅处理序列,并且在Python 3中的print_median(range(10))
之类的操作上将失败。
鉴于您正在编写包含iterables项的Python 3,我将重写您的函数以使用try
和except
并通过调用list
处理生成器传递的顺序:
def print_median(seq):
items=list(seq)
try:
median = (items[len(items) // 2 - 1] + items[len(items) // 2]) / 2
print("The median of {} is {}.".format(items, median))
except IndexError:
print("The median cannot be found.")
现在,它将按您期望的那样处理生成器和列表以及空序列:
>>> print_median([1,2,3])
The median of [1, 2, 3] is 1.5.
>>> print_median(e for e in [1,2,3])
The median of [1, 2, 3] is 1.5.
>>> print_median(range(10))
The median of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] is 4.5.
>>> print_median([])
The median cannot be found.