简体   繁体   English

递归-SyntaxError:语法无效

[英]Recursion - SyntaxError: invalid syntax

I am trying to write a recursive method as follows, but I am getting SyntaxError: invalid syntax, I wonder what I am doing wrong 我正在尝试编写如下的递归方法,但是我遇到了SyntaxError:语法无效,我想知道我在做什么错

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 给定一个非负整数num,请重复加所有数字,直到结果只有一位。

For example: 例如:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 给定num = 38,过程类似于:3 + 8 = 11,1 + 1 =2。由于2只有一位,请返回。

class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        return self.addDigits(x=sum(i for i in str(num)) if x%9<10:

Note: I am learning recursion in python, therefore rather than knowing how to solve problem, I would love to learn what I am doing wrong in my implementation. 注意:我正在学习python中的递归,因此,我不希望知道如何解决问题,而是希望了解自己在实现中做错了什么。

Updated to match the new question description: 更新以匹配新的问题描述:

def add_digits(x):
    return (x - 1) % 9 + 1 if x else 0

If you apply the brute force version of this solution (the one you were originally attempting) then you will see the output is actually the sequence listed here: https://oeis.org/A010888 . 如果应用此解决方案的蛮力版本(您最初尝试的版本),那么您将看到输出实际上是此处列出的序列: https : //oeis.org/A010888

Once we know that this is a repeating sequence we can look for patterns in the sequence, and in this case we realize that the function in this answer provides a guaranteed solution in O(1) time and space. 一旦知道这是一个重复序列,便可以在序列中寻找模式,在这种情况下,我们意识到此答案中的函数可提供O(1)时空的有保证的解决方案。

You can actually see the relationship to n % 9 by seeing this sequence here: https://oeis.org/A010878 您实际上可以通过在此处查看此序列来查看与n % 9的关系: https : //oeis.org/A010878

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM