【问题标题】:Divide each element by the next one in python在python中将每个元素除以下一个元素
【发布时间】:2018-06-14 13:16:16
【问题描述】:

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

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

【问题讨论】:

  • 您的问题不清楚。 “将每个元素除以下一个元素”是什么意思?如果您提供示例输入和输出,那会更清楚。请阅读并关注How to create a Minimal, Complete, and Verifiable example。你想让division(96, 2, 3, 2)计算96 / 2 / 3 / 2,即((96 / 2) / 3) / 2,并返回8.0吗?还是你想要1 / 96 / 2 / 3 / 2 并返回0.0008680555555555555
  • Div (/) 和 Mod (%) 应该是你的朋友。 divmod() 也是。
  • @RoryDaulton 是的,我只想这样做。即 (96 / 2 / 3 / 2,即 ((96 / 2) / 3) / 2,并返回 8.0)。得到答案,谢谢。我将查看您提供的链接,并尝试更具体地说明我的要求。

标签: python function calculator multiple-arguments


【解决方案1】:

我不确定我是否完全理解您想要什么,但如果您希望使用参数 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 将适用于乘法,但对于除法则无济于事。您需要将其设置为第一个参数,然后依次除以其余参数。

【讨论】:

  • 非常感谢。我只想这样做。非常感谢先生。
【解决方案2】:

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

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

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

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

【讨论】:

  • 啊,我要学的东西太多了!非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-12
  • 2013-11-05
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
  • 2020-07-03
相关资源
最近更新 更多