【问题标题】:the multiplication of digits squares of numbers in a range范围内数字的数字平方的乘法
【发布时间】:2019-04-02 14:32:37
【问题描述】:

我想获取一个列表,提供一个范围内的特定要求 我的代码 只能将列表中的数字相乘。 我想在列表中乘以“数字平方”

例如: 定义的范围 = (1,200)

wanted_list =[1^2,2^2,3^2,...,(34 = 3^2 * 4^2),(35 = 3^2 * 5^2),..., (199 = 1^2 * 9^2 * 9^2)]

这是我的代码

def mult(liste):
    a=1
    for i in liste:
        a*=i       #I think the problem is here
    return a

listemm = [x for x in range(1,200)]
print(listemm)
qe= [mult(int(digit) for digit in str(numb)) for numb in listemm]
print(qe)

【问题讨论】:

  • 还有什么问题?
  • 一种快速而巧妙的解决方案是将整数转换为可迭代的字符串,在这种情况下,并计算它们的平方的乘积。否则,您必须使用正确的数学方法从整数中提取数字,除以 10 并保留提醒。

标签: python python-3.x list list-manipulation


【解决方案1】:

你们很亲密。这是您自己尝试的最大范围为 30 的更正版本。问题是您的函数仅适用于两位数。在这里,我使用 if-else 条件来检查数字是否小于 10。如果是,我只需将其平方,否则将其发送到您的函数。

在函数中,您没有对数字进行平方。你也不需要listemm。您可以在列表理解中直接使用range

def mult(liste):
    a=1
    for i in liste:
        a*=i**2       # Square here (the problem was partly here)
    return a

qe= [numb**2 if numb<10 else mult(int(digit) for digit in str(numb)) for numb in range(1,30)]
print(qe)

# [1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 4, 16, 36, 64, 100, 144, 196, 256, 324]

【讨论】:

    【解决方案2】:

    我会这样做:

    r = range(1, 200)
    
    
    def reduce_prod(n):
        p = 1
        for i in str(n):
            p *= int(i)**2
        return p
    
    
    wanted_list = [reduce_prod(x) for x in r]
    

    产生:

    [1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 1, ...]
    #                                 ^
    #                                 from 10 -> 1^2 * 0^2 = 0
    

    【讨论】:

      猜你喜欢
      • 2016-01-08
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多