我具有下面的功能,并且我正在尝试对其进行修改,以便它从用户那里接收Input参数“ n”。
def difference(xs):
min_elem = xs[0]
max_elem = xs[0]
max_diff = -1
for elem in xs[1:]:
min_elem = min(elem, min_elem)
if elem > max_elem:
max_diff = max(max_diff, elem - min_elem)
max_elem = elem
return max_diff
当前,它在数组中找到最大差异。但是,我会 喜欢具有可以执行的功能:
difference(n, xs)
含义如下,给出一个数字n(例如n = 5):
difference(5, [1,2,3,4,5])
该函数应该简单地逐行打印出数组编号,然后输出该函数计算出的差值。
答案 0 :(得分:1)
您可以执行以下操作。只需再添加一个函数difference_with_input
,它将从用户那里获取输入,并使用输入的内容调用已编写的函数。
def difference(xs):
min_elem = xs[0]
max_elem = xs[0]
max_diff = -1
for elem in xs[1:]:
min_elem = min(elem, min_elem)
if elem > max_elem:
max_diff = max(max_diff, elem - min_elem)
max_elem = elem
return max_diff
def difference_with_input(n):
vals = []
for i in range(1, n+1):
vals.append(int(input("Enter value {0} : ".format(i))))
print(difference(vals))
difference_with_input(5)
输出:
Enter value 1 : 2
Enter value 2 : 1
Enter value 3 : 3
Enter value 4 : 4
Enter value 5 : 5
4