将每个元素除以 python 中的下一个元素

Divide each element by the next one in python

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

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

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

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

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

在 Python 3 中,您可以使用 functools 库中的 reduce 优雅地实现此目标。来自文档:

Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.

以及如何在您的代码中使用它的示例,这样它看起来会好得多:

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