-2

如何在除法函数中将每个元素除以下一个元素?我在调用函数中传递任意参数。提前致谢。

    def add(*number):
        numm = 0
        for num in number:
            numm =num+numm
        return numm

    def subtract(*number):
        numm = 0
        for num in number:
            numm = num-numm
        return numm

    def division(*number):
        #i am facing problem here
        # numm = 1
        # for num in number:

        try:
        if (z>=1 and z<=4):
            def get_input():
                print('Please enter numbers with a space seperation...')
                values = input()
                listOfValues = [int(x) for x in values.split()]
                return listOfValues

            val_list = get_input()

            if z==1:
                print("Addition of  numbers is:", add(*val_list))
            elif z==2:
                print("Subtraction of numbers is:", subtract(*val_list))
            elif z==3:
                print("division of numbers is:", division(*val_list))
4

2 回答 2

0

我不确定我是否完全理解您想要什么,但是如果您希望division()使用参数调用100, 3, 2并计算(100 / 3) / 2(答案:),16.6666那么

def division(*number):
    numm = number[0]
    for num in number[1:]:
        numm /= num
    return numm

它与其他函数不同,因为它们从numm设置为零开始。将其设置为 1 将适用于乘法,但对于除法将无济于事。您需要将其设置为第一个参数,然后依次除以其余参数。

于 2018-06-14T13:42:41.000 回答
0

在 Python 3 中,您可以使用reducefunctools 库优雅地实现这一目标。从文档:

将两个参数的函数从左到右累积应用于序列项,以将序列减少为单个值。例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 计算 ((((1+2)+3)+4)+5)。左侧参数 x 是累积值,右侧参数 y 是序列的更新值。如果存在可选的初始值设定项,则在计算中将其放置在序列项之前,并在序列为空时用作默认值。如果没有给出初始化程序并且序列只包含一个项目,则返回第一个项目。

并作为示例如何在您的代码中使用它,以便它看起来更好:

from functools import reduce


def get_input():
  print('Please enter numbers with a space seperation...')
  values = input()
  listOfValues = [int(x) for x in values.split()]
  return listOfValues

def add(iterable):
  return sum(iterable, start=0)
  # or reduce(lambda x, y: x + y, iterable, 0)

def subtract(iterable):
  return reduce(lambda x, y: x - y, iterable, 0)

def division(iterable):
  return reduce(lambda x, y: x / y, iterable, 1)


if __name__ == '__main__':
  try:
    print("Operation_type: ")
    value = input()
    operation_type = int(value)
  except ValueError:
    operation_type = -1

  if (operation_type >= 1 and operation_type <= 4):
    values = get_input()

    if operation_type == 1:
      print("Addition of  numbers is: {}".format(add(values)))
    elif operation_type == 2:
      print("Subtraction of numbers is: {}".format(subtract(values)))
    elif operation_type == 3:
      print("division of numbers is: {}".format(division(values)))

  else:
    print("An invalid argument was specified: `operation_type` must be in range between 1 and 4")
于 2018-06-14T14:07:37.970 回答