【问题标题】:How to count number of times integer multiplied by parts to reduce to single digit如何计算整数乘以部分的次数以减少到个位数
【发布时间】:2016-11-16 21:16:51
【问题描述】:

假设我的输入是39 - 我想正确地循环遍历这个数字的各个部分,直到最终结果是一位数(3*9 = 27、2*7 = 14、1*4 = 4),并返回乘以的次数作为输出,在本例中为3.

我对循环的基本了解使我进入了第 1 步,在该步骤中,我使用上面的示例成功地返回了 27

def times_multiplied(n):
    total = 1
    for i in map(int, str(n)):
        total *= i
    return total

另一个想法是减少数字,但还没有找到计数,是添加额外的 for 循环,但我的直觉说这是太多代码。我相信 Python 提供了一个更简单、更优雅的解决方案......

最后,当然,是捕获​​乘数计数的方法,我的直觉也说这可能与 Counter 有关...我不肯定。

请帮忙!

【问题讨论】:

  • 顺便说一句,这在基数 10 中称为multiplicative persistence of number。OEIS 条目是A031346,顺便提一下,它提供了一个类似于@GReaperEx 答案的示例 Python 函数。不幸的是,似乎没有直接的公式,所以这和你能得到的一样好。

标签: for-loop math multiplication


【解决方案1】:

您应该将times_multiplied 重命名为multiply_digits,因为它就是这样做的。然后通过循环创建真正的times_multiplied,直到结果小于十。如果我记得我的 python,这是一个可能的解决方案:

def multiply_digits(n):
    total = 1
    for i in map(int, str(n)):
        total *= i
    return total

def times_multiplied(n):
    count = 0
    result = n
    while result >= 10:
        count += 1
        result = multiply_digits(result)
    return count

在单个函数中:

def times_multiplied(n):
    count = 0
    result = n
    while result >= 10:
        count += 1
        total = 1
        for i in map(int, str(result)):
            total *= i 
        result = total
    return count

【讨论】:

  • def persistence(n): total = 1 for i in map(int, str(n)): total *= i return total count = 0 result = n while True: count += 1 result = persistence(result) if result
  • 将所有这些放在一个函数中会很麻烦。你确定要这样做吗?
  • 不,但是为了这个练习,我希望能够看到它在一个函数中是如何工作的。我同意两个函数使代码更简洁。
  • Test.assert_equals(persistence(39), 3) Test.assert_equals(persistence(4), 0) Test.assert_equals(persistence(25), 2) Test.assert_equals(persistence(999), 4)
  • count = 0 total = 1 if n
猜你喜欢
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 2015-06-11
  • 1970-01-01
  • 2012-03-16
相关资源
最近更新 更多