python 两个递归数字和函数的比较

edqdpe6u  于 2022-12-02  发布在  Python
关注(0)|答案(2)|浏览(161)

I'm stumped as to why my solution for the Recursive Digit Sum question on HackerRank is being rejected.

Background

The question:

For an input of string n and integer k, the number h is created by concatenating n "k" times. Find the "super digit" of h by recursively summing the integers until one is left.

For example:

  • n = '9875', k = 2, so h = 98759875
  • sum(98759875)= 58
  • sum(58)= 13
  • sum(13) = 4

Submissions

My Solution

def superDigit(n, k):
    h=n*k
    while len(h)>1:
        h=str(sum([int(i) for i in h]))
    return int(h)

Solution I've Found

def superDigit(n, k):
    return 1 + (k * sum(int(x) for x in n) - 1) % 9

My Inquiry to the Community

What am I missing in my solution? Yes it's not as simple as the supplied solution involving the digital root function (which I don't fully understand, I just found it online) but I don't see how my function is supplying incorrect answers. It passes most of the test cases but is rejecting for 1/3 of them.

rkue9o1l

rkue9o1l1#

这是我对你的案子的调查结果:
你不提供打字,所以我不得不检查一下,发现你用了一个str和一个int。我怎么知道?
如果使用2 str s,乘法将失败:

>>> "10"*"2"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'

如果你使用2个inth也是一个int,那么你的sum就会失败:

>>> str(sum([int(i) for i in 100]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

因此,你必须有一个int和一个str。但这也不起作用,因为int * str乘法使用的是连接,而不是“数学”加法:

>>> 10 * "2"
'2222222222'

我的解决方案建议很简单:
1.使用键入以明确说明
1.使用int s进行乘法运算,使用str s进行数字拆分
只需编辑前两行即可完成此操作:

def superDigit(n: int, k:int) -> int:
    h=str(n*k)
    while len(h)>1:
        h=str(sum([int(i) for i in h]))
    return int(h)

如果有帮助就告诉我。

ctrmrzij

ctrmrzij2#

多亏了@Tim Roberts、@Paul Hankin和@yagod的一些有用的评论,我才得以解决这个问题。事实上,这是因为超时!我所要做的就是更新一行:h=str(sum([int(i) for i in n])*(k%9))

相关问题