【问题标题】:Difference of Product and Sum of Digits [duplicate]乘积和数字和的差异[重复]
【发布时间】:2020-01-26 23:14:07
【问题描述】:

任务是找出数字乘积和数字总和的差异。例如,4 5 6 的输入将给出105。我遇到的问题是处理以前的迭代。我知道这与列表的索引有关,但我很难弄清楚。这是我的代码:

# find the difference between the product of all digits and sum of all digits
nums = input()
nums = list(nums.split())

def findProduct():
    for i in range(len(nums)):
        int(nums[i]) *= int(nums[i+1])


findProduct()

【问题讨论】:

标签: python python-3.x


【解决方案1】:

你可以使用 numpy:

import numpy as np

l = [4,5,6]

print(np.prod(l) - sum(l))

【讨论】:

    【解决方案2】:

    您可以使用内置函数来求和(称为sum),而对于乘积,将列表中的所有项目相乘是answered question:

    from functools import reduce
    
    l = [4,5,6]
    
    def findProduct(nums):
        return reduce(lambda x, y: x*y, nums) - sum(nums)
    
    print (findProduct(l))
    

    由于 Python 3.8 有一个函数math.prod,所以可以进一步简化为

    return math.prod(nums) - sum(nums)
    

    (它需要import math 而不是functools)。

    math.prod 提示来自 Heap Overflow

    【讨论】:

      【解决方案3】:

      math.prod 做你想做的事。只需将数组输入其中:

      def fn(array):
          return math.prod(array) - sum(array)
      

      【讨论】:

        【解决方案4】:
        • numpy.prod() 将数组中的所有数字相乘。
        • sum() 将数组中的所有数字相加。
        • 您可以简单地说,for i in arrayName: 并得到想要得到的东西,而不是搞乱 len

        这就是我所做的:

        import numpy as np
        Num = input("Enter the number: ")
        def getDifference(num):
            '''Takes an input of a number (as a string) and
               returns the difference between the sum and product
               of its digits'''
            numList = []
            for i in num:
                numList.append(int(i))
            Sum = sum(numlist)
            Product = np.prod(numList)
            Difference = abs(Product - Sum)
            return Difference
        print(getDifference(Num))
        

        这可以按您的意愿工作。请注意,您可以使此代码更小,如下所示:

        import numpy as np
        Num = input("Enter the number: ")
        def getDifference(num):
            '''Takes an input of a number (as a string) and
               returns the difference between the sum and product
               of its digits'''
            numList = [int(i) for i in str(num)]
            return abs(np.prod(numList)-sum(numList))
        print(getDifference(Num))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-02-01
          • 1970-01-01
          • 2012-11-12
          • 2021-04-07
          • 2020-09-26
          • 1970-01-01
          相关资源
          最近更新 更多